SemaExprCXX.cpp revision 205408
1193326Sed//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements semantic analysis for C++ expressions.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "Sema.h"
15200583Srdivacky#include "SemaInit.h"
16199482Srdivacky#include "Lookup.h"
17198092Srdivacky#include "clang/AST/ASTContext.h"
18198092Srdivacky#include "clang/AST/CXXInheritance.h"
19193326Sed#include "clang/AST/ExprCXX.h"
20204643Srdivacky#include "clang/AST/TypeLoc.h"
21198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
22198092Srdivacky#include "clang/Basic/TargetInfo.h"
23198092Srdivacky#include "clang/Lex/Preprocessor.h"
24193326Sed#include "clang/Parse/DeclSpec.h"
25204643Srdivacky#include "clang/Parse/Template.h"
26193326Sed#include "llvm/ADT/STLExtras.h"
27193326Sedusing namespace clang;
28193326Sed
29204643SrdivackyAction::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30204643Srdivacky                                        IdentifierInfo &II,
31204643Srdivacky                                        SourceLocation NameLoc,
32204643Srdivacky                                        Scope *S, const CXXScopeSpec &SS,
33204643Srdivacky                                        TypeTy *ObjectTypePtr,
34204643Srdivacky                                        bool EnteringContext) {
35204643Srdivacky  // Determine where to perform name lookup.
36204643Srdivacky
37204643Srdivacky  // FIXME: This area of the standard is very messy, and the current
38204643Srdivacky  // wording is rather unclear about which scopes we search for the
39204643Srdivacky  // destructor name; see core issues 399 and 555. Issue 399 in
40204643Srdivacky  // particular shows where the current description of destructor name
41204643Srdivacky  // lookup is completely out of line with existing practice, e.g.,
42204643Srdivacky  // this appears to be ill-formed:
43204643Srdivacky  //
44204643Srdivacky  //   namespace N {
45204643Srdivacky  //     template <typename T> struct S {
46204643Srdivacky  //       ~S();
47204643Srdivacky  //     };
48204643Srdivacky  //   }
49204643Srdivacky  //
50204643Srdivacky  //   void f(N::S<int>* s) {
51204643Srdivacky  //     s->N::S<int>::~S();
52204643Srdivacky  //   }
53204643Srdivacky  //
54204643Srdivacky  // See also PR6358 and PR6359.
55204643Srdivacky  QualType SearchType;
56204643Srdivacky  DeclContext *LookupCtx = 0;
57204643Srdivacky  bool isDependent = false;
58204643Srdivacky  bool LookInScope = false;
59204643Srdivacky
60204643Srdivacky  // If we have an object type, it's because we are in a
61204643Srdivacky  // pseudo-destructor-expression or a member access expression, and
62204643Srdivacky  // we know what type we're looking for.
63204643Srdivacky  if (ObjectTypePtr)
64204643Srdivacky    SearchType = GetTypeFromParser(ObjectTypePtr);
65204643Srdivacky
66204643Srdivacky  if (SS.isSet()) {
67204643Srdivacky    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68204643Srdivacky
69204643Srdivacky    bool AlreadySearched = false;
70204643Srdivacky    bool LookAtPrefix = true;
71204643Srdivacky    if (!getLangOptions().CPlusPlus0x) {
72204643Srdivacky      // C++ [basic.lookup.qual]p6:
73204643Srdivacky      //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74204643Srdivacky      //   the type-names are looked up as types in the scope designated by the
75204643Srdivacky      //   nested-name-specifier. In a qualified-id of the form:
76204643Srdivacky      //
77204643Srdivacky      //     ::[opt] nested-name-specifier  �� class-name
78204643Srdivacky      //
79204643Srdivacky      //   where the nested-name-specifier designates a namespace scope, and in
80204643Srdivacky      //   a qualified-id of the form:
81204643Srdivacky      //
82204643Srdivacky      //     ::opt nested-name-specifier class-name ::  �� class-name
83204643Srdivacky      //
84204643Srdivacky      //   the class-names are looked up as types in the scope designated by
85204643Srdivacky      //   the nested-name-specifier.
86204643Srdivacky      //
87204643Srdivacky      // Here, we check the first case (completely) and determine whether the
88204643Srdivacky      // code below is permitted to look at the prefix of the
89204643Srdivacky      // nested-name-specifier (as we do in C++0x).
90204643Srdivacky      DeclContext *DC = computeDeclContext(SS, EnteringContext);
91204643Srdivacky      if (DC && DC->isFileContext()) {
92204643Srdivacky        AlreadySearched = true;
93204643Srdivacky        LookupCtx = DC;
94204643Srdivacky        isDependent = false;
95204643Srdivacky      } else if (DC && isa<CXXRecordDecl>(DC))
96204643Srdivacky        LookAtPrefix = false;
97204643Srdivacky    }
98204643Srdivacky
99204643Srdivacky    // C++0x [basic.lookup.qual]p6:
100204643Srdivacky    //   If a pseudo-destructor-name (5.2.4) contains a
101204643Srdivacky    //   nested-name-specifier, the type-names are looked up as types
102204643Srdivacky    //   in the scope designated by the nested-name-specifier. Similarly, in
103204643Srdivacky    //   a qualified-id of the form:
104204643Srdivacky    //
105204643Srdivacky    //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106204643Srdivacky    //
107204643Srdivacky    //   the second class-name is looked up in the same scope as the first.
108204643Srdivacky    //
109204643Srdivacky    // To implement this, we look at the prefix of the
110204643Srdivacky    // nested-name-specifier we were given, and determine the lookup
111204643Srdivacky    // context from that.
112204643Srdivacky    //
113204643Srdivacky    // We also fold in the second case from the C++03 rules quoted further
114204643Srdivacky    // above.
115204643Srdivacky    NestedNameSpecifier *Prefix = 0;
116204643Srdivacky    if (AlreadySearched) {
117204643Srdivacky      // Nothing left to do.
118204643Srdivacky    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119204643Srdivacky      CXXScopeSpec PrefixSS;
120204643Srdivacky      PrefixSS.setScopeRep(Prefix);
121204643Srdivacky      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122204643Srdivacky      isDependent = isDependentScopeSpecifier(PrefixSS);
123204643Srdivacky    } else if (getLangOptions().CPlusPlus0x &&
124204643Srdivacky               (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125204643Srdivacky      if (!LookupCtx->isTranslationUnit())
126204643Srdivacky        LookupCtx = LookupCtx->getParent();
127204643Srdivacky      isDependent = LookupCtx && LookupCtx->isDependentContext();
128204643Srdivacky    } else if (ObjectTypePtr) {
129204643Srdivacky      LookupCtx = computeDeclContext(SearchType);
130204643Srdivacky      isDependent = SearchType->isDependentType();
131204643Srdivacky    } else {
132204643Srdivacky      LookupCtx = computeDeclContext(SS, EnteringContext);
133204643Srdivacky      isDependent = LookupCtx && LookupCtx->isDependentContext();
134204643Srdivacky    }
135204643Srdivacky
136204643Srdivacky    LookInScope = false;
137204643Srdivacky  } else if (ObjectTypePtr) {
138204643Srdivacky    // C++ [basic.lookup.classref]p3:
139204643Srdivacky    //   If the unqualified-id is ~type-name, the type-name is looked up
140204643Srdivacky    //   in the context of the entire postfix-expression. If the type T
141204643Srdivacky    //   of the object expression is of a class type C, the type-name is
142204643Srdivacky    //   also looked up in the scope of class C. At least one of the
143204643Srdivacky    //   lookups shall find a name that refers to (possibly
144204643Srdivacky    //   cv-qualified) T.
145204643Srdivacky    LookupCtx = computeDeclContext(SearchType);
146204643Srdivacky    isDependent = SearchType->isDependentType();
147204643Srdivacky    assert((isDependent || !SearchType->isIncompleteType()) &&
148204643Srdivacky           "Caller should have completed object type");
149204643Srdivacky
150204643Srdivacky    LookInScope = true;
151204643Srdivacky  } else {
152204643Srdivacky    // Perform lookup into the current scope (only).
153204643Srdivacky    LookInScope = true;
154204643Srdivacky  }
155204643Srdivacky
156204643Srdivacky  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157204643Srdivacky  for (unsigned Step = 0; Step != 2; ++Step) {
158204643Srdivacky    // Look for the name first in the computed lookup context (if we
159204643Srdivacky    // have one) and, if that fails to find a match, in the sope (if
160204643Srdivacky    // we're allowed to look there).
161204643Srdivacky    Found.clear();
162204643Srdivacky    if (Step == 0 && LookupCtx)
163204643Srdivacky      LookupQualifiedName(Found, LookupCtx);
164204643Srdivacky    else if (Step == 1 && LookInScope && S)
165204643Srdivacky      LookupName(Found, S);
166204643Srdivacky    else
167204643Srdivacky      continue;
168204643Srdivacky
169204643Srdivacky    // FIXME: Should we be suppressing ambiguities here?
170204643Srdivacky    if (Found.isAmbiguous())
171204643Srdivacky      return 0;
172204643Srdivacky
173204643Srdivacky    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174204643Srdivacky      QualType T = Context.getTypeDeclType(Type);
175204643Srdivacky
176204643Srdivacky      if (SearchType.isNull() || SearchType->isDependentType() ||
177204643Srdivacky          Context.hasSameUnqualifiedType(T, SearchType)) {
178204643Srdivacky        // We found our type!
179204643Srdivacky
180204643Srdivacky        return T.getAsOpaquePtr();
181204643Srdivacky      }
182204643Srdivacky    }
183204643Srdivacky
184204643Srdivacky    // If the name that we found is a class template name, and it is
185204643Srdivacky    // the same name as the template name in the last part of the
186204643Srdivacky    // nested-name-specifier (if present) or the object type, then
187204643Srdivacky    // this is the destructor for that class.
188204643Srdivacky    // FIXME: This is a workaround until we get real drafting for core
189204643Srdivacky    // issue 399, for which there isn't even an obvious direction.
190204643Srdivacky    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191204643Srdivacky      QualType MemberOfType;
192204643Srdivacky      if (SS.isSet()) {
193204643Srdivacky        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194204643Srdivacky          // Figure out the type of the context, if it has one.
195204962Srdivacky          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196204962Srdivacky            MemberOfType = Context.getTypeDeclType(Record);
197204643Srdivacky        }
198204643Srdivacky      }
199204643Srdivacky      if (MemberOfType.isNull())
200204643Srdivacky        MemberOfType = SearchType;
201204643Srdivacky
202204643Srdivacky      if (MemberOfType.isNull())
203204643Srdivacky        continue;
204204643Srdivacky
205204643Srdivacky      // We're referring into a class template specialization. If the
206204643Srdivacky      // class template we found is the same as the template being
207204643Srdivacky      // specialized, we found what we are looking for.
208204643Srdivacky      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209204643Srdivacky        if (ClassTemplateSpecializationDecl *Spec
210204643Srdivacky              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211204643Srdivacky          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212204643Srdivacky                Template->getCanonicalDecl())
213204643Srdivacky            return MemberOfType.getAsOpaquePtr();
214204643Srdivacky        }
215204643Srdivacky
216204643Srdivacky        continue;
217204643Srdivacky      }
218204643Srdivacky
219204643Srdivacky      // We're referring to an unresolved class template
220204643Srdivacky      // specialization. Determine whether we class template we found
221204643Srdivacky      // is the same as the template being specialized or, if we don't
222204643Srdivacky      // know which template is being specialized, that it at least
223204643Srdivacky      // has the same name.
224204643Srdivacky      if (const TemplateSpecializationType *SpecType
225204643Srdivacky            = MemberOfType->getAs<TemplateSpecializationType>()) {
226204643Srdivacky        TemplateName SpecName = SpecType->getTemplateName();
227204643Srdivacky
228204643Srdivacky        // The class template we found is the same template being
229204643Srdivacky        // specialized.
230204643Srdivacky        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231204643Srdivacky          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232204643Srdivacky            return MemberOfType.getAsOpaquePtr();
233204643Srdivacky
234204643Srdivacky          continue;
235204643Srdivacky        }
236204643Srdivacky
237204643Srdivacky        // The class template we found has the same name as the
238204643Srdivacky        // (dependent) template name being specialized.
239204643Srdivacky        if (DependentTemplateName *DepTemplate
240204643Srdivacky                                    = SpecName.getAsDependentTemplateName()) {
241204643Srdivacky          if (DepTemplate->isIdentifier() &&
242204643Srdivacky              DepTemplate->getIdentifier() == Template->getIdentifier())
243204643Srdivacky            return MemberOfType.getAsOpaquePtr();
244204643Srdivacky
245204643Srdivacky          continue;
246204643Srdivacky        }
247204643Srdivacky      }
248204643Srdivacky    }
249204643Srdivacky  }
250204643Srdivacky
251204643Srdivacky  if (isDependent) {
252204643Srdivacky    // We didn't find our type, but that's okay: it's dependent
253204643Srdivacky    // anyway.
254204643Srdivacky    NestedNameSpecifier *NNS = 0;
255204643Srdivacky    SourceRange Range;
256204643Srdivacky    if (SS.isSet()) {
257204643Srdivacky      NNS = (NestedNameSpecifier *)SS.getScopeRep();
258204643Srdivacky      Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259204643Srdivacky    } else {
260204643Srdivacky      NNS = NestedNameSpecifier::Create(Context, &II);
261204643Srdivacky      Range = SourceRange(NameLoc);
262204643Srdivacky    }
263204643Srdivacky
264204643Srdivacky    return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
265204643Srdivacky  }
266204643Srdivacky
267204643Srdivacky  if (ObjectTypePtr)
268204643Srdivacky    Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269204643Srdivacky      << &II;
270204643Srdivacky  else
271204643Srdivacky    Diag(NameLoc, diag::err_destructor_class_name);
272204643Srdivacky
273204643Srdivacky  return 0;
274204643Srdivacky}
275204643Srdivacky
276193326Sed/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
277193326SedAction::OwningExprResult
278193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279193326Sed                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
280198092Srdivacky  if (!StdNamespace)
281193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
282198092Srdivacky
283201361Srdivacky  if (isType) {
284201361Srdivacky    // C++ [expr.typeid]p4:
285201361Srdivacky    //   The top-level cv-qualifiers of the lvalue expression or the type-id
286201361Srdivacky    //   that is the operand of typeid are always ignored.
287198092Srdivacky    // FIXME: Preserve type source info.
288201361Srdivacky    // FIXME: Preserve the type before we stripped the cv-qualifiers?
289201361Srdivacky    QualType T = GetTypeFromParser(TyOrExpr);
290201361Srdivacky    if (T.isNull())
291201361Srdivacky      return ExprError();
292201361Srdivacky
293201361Srdivacky    // C++ [expr.typeid]p4:
294201361Srdivacky    //   If the type of the type-id is a class type or a reference to a class
295201361Srdivacky    //   type, the class shall be completely-defined.
296201361Srdivacky    QualType CheckT = T;
297201361Srdivacky    if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
298201361Srdivacky      CheckT = RefType->getPointeeType();
299201361Srdivacky
300201361Srdivacky    if (CheckT->getAs<RecordType>() &&
301201361Srdivacky        RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
302201361Srdivacky      return ExprError();
303201361Srdivacky
304201361Srdivacky    TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
305201361Srdivacky  }
306198092Srdivacky
307193326Sed  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
308199482Srdivacky  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309199482Srdivacky  LookupQualifiedName(R, StdNamespace);
310200583Srdivacky  RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
311193326Sed  if (!TypeInfoRecordDecl)
312193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
313193326Sed
314193326Sed  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315193326Sed
316194711Sed  if (!isType) {
317194711Sed    bool isUnevaluatedOperand = true;
318194711Sed    Expr *E = static_cast<Expr *>(TyOrExpr);
319201361Srdivacky    if (E && !E->isTypeDependent()) {
320194711Sed      QualType T = E->getType();
321198092Srdivacky      if (const RecordType *RecordT = T->getAs<RecordType>()) {
322194711Sed        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
323201361Srdivacky        // C++ [expr.typeid]p3:
324203955Srdivacky        //   [...] If the type of the expression is a class type, the class
325203955Srdivacky        //   shall be completely-defined.
326203955Srdivacky        if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
327203955Srdivacky          return ExprError();
328203955Srdivacky
329203955Srdivacky        // C++ [expr.typeid]p3:
330201361Srdivacky        //   When typeid is applied to an expression other than an lvalue of a
331201361Srdivacky        //   polymorphic class type [...] [the] expression is an unevaluated
332201361Srdivacky        //   operand. [...]
333201361Srdivacky        if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
334194711Sed          isUnevaluatedOperand = false;
335194711Sed      }
336201361Srdivacky
337201361Srdivacky      // C++ [expr.typeid]p4:
338201361Srdivacky      //   [...] If the type of the type-id is a reference to a possibly
339201361Srdivacky      //   cv-qualified type, the result of the typeid expression refers to a
340201361Srdivacky      //   std::type_info object representing the cv-unqualified referenced
341201361Srdivacky      //   type.
342201361Srdivacky      if (T.hasQualifiers()) {
343201361Srdivacky        ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
344201361Srdivacky                          E->isLvalue(Context));
345201361Srdivacky        TyOrExpr = E;
346201361Srdivacky      }
347194711Sed    }
348198092Srdivacky
349199990Srdivacky    // If this is an unevaluated operand, clear out the set of
350199990Srdivacky    // declaration references we have been computing and eliminate any
351199990Srdivacky    // temporaries introduced in its computation.
352194711Sed    if (isUnevaluatedOperand)
353199990Srdivacky      ExprEvalContexts.back().Context = Unevaluated;
354194711Sed  }
355198092Srdivacky
356193326Sed  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357193326Sed                                           TypeInfoType.withConst(),
358193326Sed                                           SourceRange(OpLoc, RParenLoc)));
359193326Sed}
360193326Sed
361193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals.
362193326SedAction::OwningExprResult
363193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
364193326Sed  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
365193326Sed         "Unknown C++ Boolean value!");
366193326Sed  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367193326Sed                                                Context.BoolTy, OpLoc));
368193326Sed}
369193326Sed
370193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
371193326SedAction::OwningExprResult
372193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
373193326Sed  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
374193326Sed}
375193326Sed
376193326Sed/// ActOnCXXThrow - Parse throw expressions.
377193326SedAction::OwningExprResult
378193326SedSema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
379193326Sed  Expr *Ex = E.takeAs<Expr>();
380193326Sed  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
381193326Sed    return ExprError();
382193326Sed  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
383193326Sed}
384193326Sed
385193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw.
386193326Sedbool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
387193326Sed  // C++ [except.throw]p3:
388201361Srdivacky  //   A throw-expression initializes a temporary object, called the exception
389201361Srdivacky  //   object, the type of which is determined by removing any top-level
390201361Srdivacky  //   cv-qualifiers from the static type of the operand of throw and adjusting
391201361Srdivacky  //   the type from "array of T" or "function returning T" to "pointer to T"
392201361Srdivacky  //   or "pointer to function returning T", [...]
393201361Srdivacky  if (E->getType().hasQualifiers())
394201361Srdivacky    ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
395201361Srdivacky                      E->isLvalue(Context) == Expr::LV_Valid);
396201361Srdivacky
397193326Sed  DefaultFunctionArrayConversion(E);
398193326Sed
399193326Sed  //   If the type of the exception would be an incomplete type or a pointer
400193326Sed  //   to an incomplete type other than (cv) void the program is ill-formed.
401193326Sed  QualType Ty = E->getType();
402193326Sed  int isPointer = 0;
403198092Srdivacky  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
404193326Sed    Ty = Ptr->getPointeeType();
405193326Sed    isPointer = 1;
406193326Sed  }
407193326Sed  if (!isPointer || !Ty->isVoidType()) {
408193326Sed    if (RequireCompleteType(ThrowLoc, Ty,
409198092Srdivacky                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
410198092Srdivacky                                            : diag::err_throw_incomplete)
411198092Srdivacky                              << E->getSourceRange()))
412193326Sed      return true;
413204643Srdivacky
414204643Srdivacky    // FIXME: This is just a hack to mark the copy constructor referenced.
415204643Srdivacky    // This should go away when the next FIXME is fixed.
416204643Srdivacky    const RecordType *RT = Ty->getAs<RecordType>();
417204643Srdivacky    if (!RT)
418204643Srdivacky      return false;
419204643Srdivacky
420204643Srdivacky    const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
421204643Srdivacky    if (RD->hasTrivialCopyConstructor())
422204643Srdivacky      return false;
423204643Srdivacky    CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
424204643Srdivacky    MarkDeclarationReferenced(ThrowLoc, CopyCtor);
425193326Sed  }
426193326Sed
427193326Sed  // FIXME: Construct a temporary here.
428193326Sed  return false;
429193326Sed}
430193326Sed
431193326SedAction::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
432193326Sed  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
433193326Sed  /// is a non-lvalue expression whose value is the address of the object for
434193326Sed  /// which the function is called.
435193326Sed
436193326Sed  if (!isa<FunctionDecl>(CurContext))
437193326Sed    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
438193326Sed
439193326Sed  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
440193326Sed    if (MD->isInstance())
441193326Sed      return Owned(new (Context) CXXThisExpr(ThisLoc,
442202379Srdivacky                                             MD->getThisType(Context),
443202379Srdivacky                                             /*isImplicit=*/false));
444193326Sed
445193326Sed  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
446193326Sed}
447193326Sed
448193326Sed/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
449193326Sed/// Can be interpreted either as function-style casting ("int(x)")
450193326Sed/// or class type construction ("ClassType(x,y,z)")
451193326Sed/// or creation of a value-initialized type ("int()").
452193326SedAction::OwningExprResult
453193326SedSema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
454193326Sed                                SourceLocation LParenLoc,
455193326Sed                                MultiExprArg exprs,
456193326Sed                                SourceLocation *CommaLocs,
457193326Sed                                SourceLocation RParenLoc) {
458203955Srdivacky  if (!TypeRep)
459203955Srdivacky    return ExprError();
460203955Srdivacky
461202879Srdivacky  TypeSourceInfo *TInfo;
462202879Srdivacky  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
463202879Srdivacky  if (!TInfo)
464202879Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
465193326Sed  unsigned NumExprs = exprs.size();
466193326Sed  Expr **Exprs = (Expr**)exprs.get();
467193326Sed  SourceLocation TyBeginLoc = TypeRange.getBegin();
468193326Sed  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
469193326Sed
470193326Sed  if (Ty->isDependentType() ||
471193326Sed      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
472193326Sed    exprs.release();
473198092Srdivacky
474198092Srdivacky    return Owned(CXXUnresolvedConstructExpr::Create(Context,
475198092Srdivacky                                                    TypeRange.getBegin(), Ty,
476193326Sed                                                    LParenLoc,
477193326Sed                                                    Exprs, NumExprs,
478193326Sed                                                    RParenLoc));
479193326Sed  }
480193326Sed
481198092Srdivacky  if (Ty->isArrayType())
482198092Srdivacky    return ExprError(Diag(TyBeginLoc,
483198092Srdivacky                          diag::err_value_init_for_array_type) << FullRange);
484198092Srdivacky  if (!Ty->isVoidType() &&
485198092Srdivacky      RequireCompleteType(TyBeginLoc, Ty,
486198092Srdivacky                          PDiag(diag::err_invalid_incomplete_type_use)
487198092Srdivacky                            << FullRange))
488198092Srdivacky    return ExprError();
489198893Srdivacky
490198092Srdivacky  if (RequireNonAbstractType(TyBeginLoc, Ty,
491198092Srdivacky                             diag::err_allocation_of_abstract_type))
492198092Srdivacky    return ExprError();
493198092Srdivacky
494198092Srdivacky
495193326Sed  // C++ [expr.type.conv]p1:
496193326Sed  // If the expression list is a single expression, the type conversion
497193326Sed  // expression is equivalent (in definedness, and if defined in meaning) to the
498193326Sed  // corresponding cast expression.
499193326Sed  //
500193326Sed  if (NumExprs == 1) {
501198092Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
502198092Srdivacky    CXXMethodDecl *Method = 0;
503198092Srdivacky    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
504198092Srdivacky                       /*FunctionalStyle=*/true))
505193326Sed      return ExprError();
506198092Srdivacky
507193326Sed    exprs.release();
508198092Srdivacky    if (Method) {
509198092Srdivacky      OwningExprResult CastArg
510198092Srdivacky        = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
511198092Srdivacky                               Kind, Method, Owned(Exprs[0]));
512198092Srdivacky      if (CastArg.isInvalid())
513198092Srdivacky        return ExprError();
514198092Srdivacky
515198092Srdivacky      Exprs[0] = CastArg.takeAs<Expr>();
516198092Srdivacky    }
517198092Srdivacky
518193326Sed    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
519202879Srdivacky                                                     TInfo, TyBeginLoc, Kind,
520198092Srdivacky                                                     Exprs[0], RParenLoc));
521193326Sed  }
522193326Sed
523198092Srdivacky  if (const RecordType *RT = Ty->getAs<RecordType>()) {
524193326Sed    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
525193326Sed
526198092Srdivacky    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
527198092Srdivacky        !Record->hasTrivialDestructor()) {
528203955Srdivacky      InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
529203955Srdivacky      InitializationKind Kind
530203955Srdivacky        = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
531203955Srdivacky                                                      LParenLoc, RParenLoc)
532203955Srdivacky                   : InitializationKind::CreateValue(TypeRange.getBegin(),
533203955Srdivacky                                                     LParenLoc, RParenLoc);
534203955Srdivacky      InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
535203955Srdivacky      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
536203955Srdivacky                                                move(exprs));
537193326Sed
538203955Srdivacky      // FIXME: Improve AST representation?
539203955Srdivacky      return move(Result);
540193326Sed    }
541193326Sed
542193326Sed    // Fall through to value-initialize an object of class type that
543193326Sed    // doesn't have a user-declared default constructor.
544193326Sed  }
545193326Sed
546193326Sed  // C++ [expr.type.conv]p1:
547193326Sed  // If the expression list specifies more than a single value, the type shall
548193326Sed  // be a class with a suitably declared constructor.
549193326Sed  //
550193326Sed  if (NumExprs > 1)
551193326Sed    return ExprError(Diag(CommaLocs[0],
552193326Sed                          diag::err_builtin_func_cast_more_than_one_arg)
553193326Sed      << FullRange);
554193326Sed
555193326Sed  assert(NumExprs == 0 && "Expected 0 expressions");
556193326Sed  // C++ [expr.type.conv]p2:
557193326Sed  // The expression T(), where T is a simple-type-specifier for a non-array
558193326Sed  // complete object type or the (possibly cv-qualified) void type, creates an
559193326Sed  // rvalue of the specified type, which is value-initialized.
560193326Sed  //
561193326Sed  exprs.release();
562193326Sed  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
563193326Sed}
564193326Sed
565193326Sed
566193326Sed/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
567193326Sed/// @code new (memory) int[size][4] @endcode
568193326Sed/// or
569193326Sed/// @code ::new Foo(23, "hello") @endcode
570193326Sed/// For the interpretation of this heap of arguments, consult the base version.
571193326SedAction::OwningExprResult
572193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
573193326Sed                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
574193326Sed                  SourceLocation PlacementRParen, bool ParenTypeId,
575193326Sed                  Declarator &D, SourceLocation ConstructorLParen,
576193326Sed                  MultiExprArg ConstructorArgs,
577198092Srdivacky                  SourceLocation ConstructorRParen) {
578193326Sed  Expr *ArraySize = 0;
579193326Sed  // If the specified type is an array, unwrap it and save the expression.
580193326Sed  if (D.getNumTypeObjects() > 0 &&
581193326Sed      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
582193326Sed    DeclaratorChunk &Chunk = D.getTypeObject(0);
583193326Sed    if (Chunk.Arr.hasStatic)
584193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
585193326Sed        << D.getSourceRange());
586193326Sed    if (!Chunk.Arr.NumElts)
587193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
588193326Sed        << D.getSourceRange());
589198893Srdivacky
590198893Srdivacky    if (ParenTypeId) {
591198893Srdivacky      // Can't have dynamic array size when the type-id is in parentheses.
592198893Srdivacky      Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
593198893Srdivacky      if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
594198893Srdivacky          !NumElts->isIntegerConstantExpr(Context)) {
595198893Srdivacky        Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
596198893Srdivacky          << NumElts->getSourceRange();
597198893Srdivacky        return ExprError();
598198893Srdivacky      }
599198893Srdivacky    }
600198893Srdivacky
601193326Sed    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
602198893Srdivacky    D.DropFirstTypeObject();
603193326Sed  }
604193326Sed
605198092Srdivacky  // Every dimension shall be of constant size.
606198893Srdivacky  if (ArraySize) {
607198893Srdivacky    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
608198092Srdivacky      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
609198092Srdivacky        break;
610193326Sed
611198092Srdivacky      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
612198092Srdivacky      if (Expr *NumElts = (Expr *)Array.NumElts) {
613198092Srdivacky        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
614198092Srdivacky            !NumElts->isIntegerConstantExpr(Context)) {
615198092Srdivacky          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
616198092Srdivacky            << NumElts->getSourceRange();
617198092Srdivacky          return ExprError();
618198092Srdivacky        }
619198092Srdivacky      }
620193326Sed    }
621193326Sed  }
622198893Srdivacky
623200583Srdivacky  //FIXME: Store TypeSourceInfo in CXXNew expression.
624200583Srdivacky  TypeSourceInfo *TInfo = 0;
625200583Srdivacky  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
626198092Srdivacky  if (D.isInvalidType())
627198092Srdivacky    return ExprError();
628199990Srdivacky
629198092Srdivacky  return BuildCXXNew(StartLoc, UseGlobal,
630193326Sed                     PlacementLParen,
631198092Srdivacky                     move(PlacementArgs),
632193326Sed                     PlacementRParen,
633193326Sed                     ParenTypeId,
634198092Srdivacky                     AllocType,
635193326Sed                     D.getSourceRange().getBegin(),
636193326Sed                     D.getSourceRange(),
637193326Sed                     Owned(ArraySize),
638193326Sed                     ConstructorLParen,
639193326Sed                     move(ConstructorArgs),
640193326Sed                     ConstructorRParen);
641193326Sed}
642193326Sed
643198092SrdivackySema::OwningExprResult
644193326SedSema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
645193326Sed                  SourceLocation PlacementLParen,
646193326Sed                  MultiExprArg PlacementArgs,
647193326Sed                  SourceLocation PlacementRParen,
648198092Srdivacky                  bool ParenTypeId,
649193326Sed                  QualType AllocType,
650193326Sed                  SourceLocation TypeLoc,
651193326Sed                  SourceRange TypeRange,
652193326Sed                  ExprArg ArraySizeE,
653193326Sed                  SourceLocation ConstructorLParen,
654193326Sed                  MultiExprArg ConstructorArgs,
655193326Sed                  SourceLocation ConstructorRParen) {
656193326Sed  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
657193326Sed    return ExprError();
658193326Sed
659193326Sed  QualType ResultType = Context.getPointerType(AllocType);
660193326Sed
661193326Sed  // That every array dimension except the first is constant was already
662193326Sed  // checked by the type check above.
663193326Sed
664193326Sed  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
665193326Sed  //   or enumeration type with a non-negative value."
666193326Sed  Expr *ArraySize = (Expr *)ArraySizeE.get();
667193326Sed  if (ArraySize && !ArraySize->isTypeDependent()) {
668193326Sed    QualType SizeType = ArraySize->getType();
669193326Sed    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
670193326Sed      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
671193326Sed                            diag::err_array_size_not_integral)
672193326Sed        << SizeType << ArraySize->getSourceRange());
673193326Sed    // Let's see if this is a constant < 0. If so, we reject it out of hand.
674193326Sed    // We don't care about special rules, so we tell the machinery it's not
675193326Sed    // evaluated - it gives us a result in more cases.
676193326Sed    if (!ArraySize->isValueDependent()) {
677193326Sed      llvm::APSInt Value;
678193326Sed      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
679193326Sed        if (Value < llvm::APSInt(
680198092Srdivacky                        llvm::APInt::getNullValue(Value.getBitWidth()),
681198092Srdivacky                                 Value.isUnsigned()))
682193326Sed          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683193326Sed                           diag::err_typecheck_negative_array_size)
684193326Sed            << ArraySize->getSourceRange());
685193326Sed      }
686193326Sed    }
687198092Srdivacky
688198398Srdivacky    ImpCastExprToType(ArraySize, Context.getSizeType(),
689198398Srdivacky                      CastExpr::CK_IntegralCast);
690193326Sed  }
691193326Sed
692193326Sed  FunctionDecl *OperatorNew = 0;
693193326Sed  FunctionDecl *OperatorDelete = 0;
694193326Sed  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
695193326Sed  unsigned NumPlaceArgs = PlacementArgs.size();
696199990Srdivacky
697193326Sed  if (!AllocType->isDependentType() &&
698193326Sed      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
699193326Sed      FindAllocationFunctions(StartLoc,
700193326Sed                              SourceRange(PlacementLParen, PlacementRParen),
701193326Sed                              UseGlobal, AllocType, ArraySize, PlaceArgs,
702193326Sed                              NumPlaceArgs, OperatorNew, OperatorDelete))
703193326Sed    return ExprError();
704199990Srdivacky  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
705199990Srdivacky  if (OperatorNew) {
706199990Srdivacky    // Add default arguments, if any.
707199990Srdivacky    const FunctionProtoType *Proto =
708199990Srdivacky      OperatorNew->getType()->getAs<FunctionProtoType>();
709199990Srdivacky    VariadicCallType CallType =
710199990Srdivacky      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
711199990Srdivacky    bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
712199990Srdivacky                                          Proto, 1, PlaceArgs, NumPlaceArgs,
713199990Srdivacky                                          AllPlaceArgs, CallType);
714199990Srdivacky    if (Invalid)
715199990Srdivacky      return ExprError();
716199990Srdivacky
717199990Srdivacky    NumPlaceArgs = AllPlaceArgs.size();
718199990Srdivacky    if (NumPlaceArgs > 0)
719199990Srdivacky      PlaceArgs = &AllPlaceArgs[0];
720199990Srdivacky  }
721199990Srdivacky
722193326Sed  bool Init = ConstructorLParen.isValid();
723193326Sed  // --- Choosing a constructor ---
724193326Sed  CXXConstructorDecl *Constructor = 0;
725193326Sed  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
726193326Sed  unsigned NumConsArgs = ConstructorArgs.size();
727199482Srdivacky  ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
728199482Srdivacky
729201361Srdivacky  if (!AllocType->isDependentType() &&
730201361Srdivacky      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
731201361Srdivacky    // C++0x [expr.new]p15:
732201361Srdivacky    //   A new-expression that creates an object of type T initializes that
733201361Srdivacky    //   object as follows:
734201361Srdivacky    InitializationKind Kind
735201361Srdivacky    //     - If the new-initializer is omitted, the object is default-
736201361Srdivacky    //       initialized (8.5); if no initialization is performed,
737201361Srdivacky    //       the object has indeterminate value
738201361Srdivacky      = !Init? InitializationKind::CreateDefault(TypeLoc)
739201361Srdivacky    //     - Otherwise, the new-initializer is interpreted according to the
740201361Srdivacky    //       initialization rules of 8.5 for direct-initialization.
741201361Srdivacky             : InitializationKind::CreateDirect(TypeLoc,
742201361Srdivacky                                                ConstructorLParen,
743201361Srdivacky                                                ConstructorRParen);
744201361Srdivacky
745201361Srdivacky    InitializedEntity Entity
746201361Srdivacky      = InitializedEntity::InitializeNew(StartLoc, AllocType);
747201361Srdivacky    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
748201361Srdivacky    OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
749201361Srdivacky                                                move(ConstructorArgs));
750201361Srdivacky    if (FullInit.isInvalid())
751193326Sed      return ExprError();
752201361Srdivacky
753201361Srdivacky    // FullInit is our initializer; walk through it to determine if it's a
754201361Srdivacky    // constructor call, which CXXNewExpr handles directly.
755201361Srdivacky    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
756201361Srdivacky      if (CXXBindTemporaryExpr *Binder
757201361Srdivacky            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
758201361Srdivacky        FullInitExpr = Binder->getSubExpr();
759201361Srdivacky      if (CXXConstructExpr *Construct
760201361Srdivacky                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
761201361Srdivacky        Constructor = Construct->getConstructor();
762201361Srdivacky        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
763201361Srdivacky                                         AEnd = Construct->arg_end();
764201361Srdivacky             A != AEnd; ++A)
765201361Srdivacky          ConvertedConstructorArgs.push_back(A->Retain());
766201361Srdivacky      } else {
767201361Srdivacky        // Take the converted initializer.
768201361Srdivacky        ConvertedConstructorArgs.push_back(FullInit.release());
769201361Srdivacky      }
770201361Srdivacky    } else {
771201361Srdivacky      // No initialization required.
772201361Srdivacky    }
773201361Srdivacky
774201361Srdivacky    // Take the converted arguments and use them for the new expression.
775198092Srdivacky    NumConsArgs = ConvertedConstructorArgs.size();
776198092Srdivacky    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
777193326Sed  }
778201361Srdivacky
779204643Srdivacky  // Mark the new and delete operators as referenced.
780204643Srdivacky  if (OperatorNew)
781204643Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorNew);
782204643Srdivacky  if (OperatorDelete)
783204643Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorDelete);
784204643Srdivacky
785193326Sed  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
786198398Srdivacky
787193326Sed  PlacementArgs.release();
788193326Sed  ConstructorArgs.release();
789193326Sed  ArraySizeE.release();
790203955Srdivacky  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
791203955Srdivacky                                        PlaceArgs, NumPlaceArgs, ParenTypeId,
792203955Srdivacky                                        ArraySize, Constructor, Init,
793203955Srdivacky                                        ConsArgs, NumConsArgs, OperatorDelete,
794203955Srdivacky                                        ResultType, StartLoc,
795203955Srdivacky                                        Init ? ConstructorRParen :
796203955Srdivacky                                               SourceLocation()));
797193326Sed}
798193326Sed
799193326Sed/// CheckAllocatedType - Checks that a type is suitable as the allocated type
800193326Sed/// in a new-expression.
801193326Sed/// dimension off and stores the size expression in ArraySize.
802193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
803198092Srdivacky                              SourceRange R) {
804193326Sed  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
805193326Sed  //   abstract class type or array thereof.
806193326Sed  if (AllocType->isFunctionType())
807193326Sed    return Diag(Loc, diag::err_bad_new_type)
808193326Sed      << AllocType << 0 << R;
809193326Sed  else if (AllocType->isReferenceType())
810193326Sed    return Diag(Loc, diag::err_bad_new_type)
811193326Sed      << AllocType << 1 << R;
812193326Sed  else if (!AllocType->isDependentType() &&
813193326Sed           RequireCompleteType(Loc, AllocType,
814198092Srdivacky                               PDiag(diag::err_new_incomplete_type)
815198092Srdivacky                                 << R))
816193326Sed    return true;
817193326Sed  else if (RequireNonAbstractType(Loc, AllocType,
818193326Sed                                  diag::err_allocation_of_abstract_type))
819193326Sed    return true;
820193326Sed
821193326Sed  return false;
822193326Sed}
823193326Sed
824204643Srdivacky/// \brief Determine whether the given function is a non-placement
825204643Srdivacky/// deallocation function.
826204643Srdivackystatic bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
827204643Srdivacky  if (FD->isInvalidDecl())
828204643Srdivacky    return false;
829204643Srdivacky
830204643Srdivacky  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
831204643Srdivacky    return Method->isUsualDeallocationFunction();
832204643Srdivacky
833204643Srdivacky  return ((FD->getOverloadedOperator() == OO_Delete ||
834204643Srdivacky           FD->getOverloadedOperator() == OO_Array_Delete) &&
835204643Srdivacky          FD->getNumParams() == 1);
836204643Srdivacky}
837204643Srdivacky
838193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete
839193326Sed/// that are appropriate for the allocation.
840193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
841193326Sed                                   bool UseGlobal, QualType AllocType,
842193326Sed                                   bool IsArray, Expr **PlaceArgs,
843193326Sed                                   unsigned NumPlaceArgs,
844193326Sed                                   FunctionDecl *&OperatorNew,
845198092Srdivacky                                   FunctionDecl *&OperatorDelete) {
846193326Sed  // --- Choosing an allocation function ---
847193326Sed  // C++ 5.3.4p8 - 14 & 18
848193326Sed  // 1) If UseGlobal is true, only look in the global scope. Else, also look
849193326Sed  //   in the scope of the allocated class.
850193326Sed  // 2) If an array size is given, look for operator new[], else look for
851193326Sed  //   operator new.
852193326Sed  // 3) The first argument is always size_t. Append the arguments from the
853193326Sed  //   placement form.
854193326Sed
855193326Sed  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
856193326Sed  // We don't care about the actual value of this argument.
857193326Sed  // FIXME: Should the Sema create the expression and embed it in the syntax
858193326Sed  // tree? Or should the consumer just recalculate the value?
859198092Srdivacky  IntegerLiteral Size(llvm::APInt::getNullValue(
860198092Srdivacky                      Context.Target.getPointerWidth(0)),
861198092Srdivacky                      Context.getSizeType(),
862198092Srdivacky                      SourceLocation());
863198092Srdivacky  AllocArgs[0] = &Size;
864193326Sed  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
865193326Sed
866204643Srdivacky  // C++ [expr.new]p8:
867204643Srdivacky  //   If the allocated type is a non-array type, the allocation
868204643Srdivacky  //   function���s name is operator new and the deallocation function���s
869204643Srdivacky  //   name is operator delete. If the allocated type is an array
870204643Srdivacky  //   type, the allocation function���s name is operator new[] and the
871204643Srdivacky  //   deallocation function���s name is operator delete[].
872193326Sed  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
873193326Sed                                        IsArray ? OO_Array_New : OO_New);
874204643Srdivacky  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
875204643Srdivacky                                        IsArray ? OO_Array_Delete : OO_Delete);
876204643Srdivacky
877193326Sed  if (AllocType->isRecordType() && !UseGlobal) {
878198092Srdivacky    CXXRecordDecl *Record
879198092Srdivacky      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
880193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
881193326Sed                          AllocArgs.size(), Record, /*AllowMissing=*/true,
882193326Sed                          OperatorNew))
883193326Sed      return true;
884193326Sed  }
885193326Sed  if (!OperatorNew) {
886193326Sed    // Didn't find a member overload. Look for a global one.
887193326Sed    DeclareGlobalNewDelete();
888193326Sed    DeclContext *TUDecl = Context.getTranslationUnitDecl();
889193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
890193326Sed                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
891193326Sed                          OperatorNew))
892193326Sed      return true;
893193326Sed  }
894193326Sed
895193326Sed  // FindAllocationOverload can change the passed in arguments, so we need to
896193326Sed  // copy them back.
897193326Sed  if (NumPlaceArgs > 0)
898193326Sed    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
899198092Srdivacky
900204643Srdivacky  // C++ [expr.new]p19:
901204643Srdivacky  //
902204643Srdivacky  //   If the new-expression begins with a unary :: operator, the
903204643Srdivacky  //   deallocation function���s name is looked up in the global
904204643Srdivacky  //   scope. Otherwise, if the allocated type is a class type T or an
905204643Srdivacky  //   array thereof, the deallocation function���s name is looked up in
906204643Srdivacky  //   the scope of T. If this lookup fails to find the name, or if
907204643Srdivacky  //   the allocated type is not a class type or array thereof, the
908204643Srdivacky  //   deallocation function���s name is looked up in the global scope.
909204643Srdivacky  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
910204643Srdivacky  if (AllocType->isRecordType() && !UseGlobal) {
911204643Srdivacky    CXXRecordDecl *RD
912204643Srdivacky      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
913204643Srdivacky    LookupQualifiedName(FoundDelete, RD);
914204643Srdivacky  }
915205408Srdivacky  if (FoundDelete.isAmbiguous())
916205408Srdivacky    return true; // FIXME: clean up expressions?
917204643Srdivacky
918204643Srdivacky  if (FoundDelete.empty()) {
919204643Srdivacky    DeclareGlobalNewDelete();
920204643Srdivacky    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
921204643Srdivacky  }
922204643Srdivacky
923204643Srdivacky  FoundDelete.suppressDiagnostics();
924205408Srdivacky
925205408Srdivacky  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
926205408Srdivacky
927205408Srdivacky  if (NumPlaceArgs > 0) {
928204643Srdivacky    // C++ [expr.new]p20:
929204643Srdivacky    //   A declaration of a placement deallocation function matches the
930204643Srdivacky    //   declaration of a placement allocation function if it has the
931204643Srdivacky    //   same number of parameters and, after parameter transformations
932204643Srdivacky    //   (8.3.5), all parameter types except the first are
933204643Srdivacky    //   identical. [...]
934204643Srdivacky    //
935204643Srdivacky    // To perform this comparison, we compute the function type that
936204643Srdivacky    // the deallocation function should have, and use that type both
937204643Srdivacky    // for template argument deduction and for comparison purposes.
938204643Srdivacky    QualType ExpectedFunctionType;
939204643Srdivacky    {
940204643Srdivacky      const FunctionProtoType *Proto
941204643Srdivacky        = OperatorNew->getType()->getAs<FunctionProtoType>();
942204643Srdivacky      llvm::SmallVector<QualType, 4> ArgTypes;
943204643Srdivacky      ArgTypes.push_back(Context.VoidPtrTy);
944204643Srdivacky      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
945204643Srdivacky        ArgTypes.push_back(Proto->getArgType(I));
946204643Srdivacky
947204643Srdivacky      ExpectedFunctionType
948204643Srdivacky        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
949204643Srdivacky                                  ArgTypes.size(),
950204643Srdivacky                                  Proto->isVariadic(),
951204643Srdivacky                                  0, false, false, 0, 0, false, CC_Default);
952204643Srdivacky    }
953204643Srdivacky
954204643Srdivacky    for (LookupResult::iterator D = FoundDelete.begin(),
955204643Srdivacky                             DEnd = FoundDelete.end();
956204643Srdivacky         D != DEnd; ++D) {
957204643Srdivacky      FunctionDecl *Fn = 0;
958204643Srdivacky      if (FunctionTemplateDecl *FnTmpl
959204643Srdivacky            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
960204643Srdivacky        // Perform template argument deduction to try to match the
961204643Srdivacky        // expected function type.
962204643Srdivacky        TemplateDeductionInfo Info(Context, StartLoc);
963204643Srdivacky        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
964204643Srdivacky          continue;
965204643Srdivacky      } else
966204643Srdivacky        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
967204643Srdivacky
968204643Srdivacky      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
969205408Srdivacky        Matches.push_back(std::make_pair(D.getPair(), Fn));
970204643Srdivacky    }
971204643Srdivacky  } else {
972204643Srdivacky    // C++ [expr.new]p20:
973204643Srdivacky    //   [...] Any non-placement deallocation function matches a
974204643Srdivacky    //   non-placement allocation function. [...]
975204643Srdivacky    for (LookupResult::iterator D = FoundDelete.begin(),
976204643Srdivacky                             DEnd = FoundDelete.end();
977204643Srdivacky         D != DEnd; ++D) {
978204643Srdivacky      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
979204643Srdivacky        if (isNonPlacementDeallocationFunction(Fn))
980205408Srdivacky          Matches.push_back(std::make_pair(D.getPair(), Fn));
981204643Srdivacky    }
982204643Srdivacky  }
983204643Srdivacky
984204643Srdivacky  // C++ [expr.new]p20:
985204643Srdivacky  //   [...] If the lookup finds a single matching deallocation
986204643Srdivacky  //   function, that function will be called; otherwise, no
987204643Srdivacky  //   deallocation function will be called.
988204643Srdivacky  if (Matches.size() == 1) {
989205408Srdivacky    OperatorDelete = Matches[0].second;
990204643Srdivacky
991204643Srdivacky    // C++0x [expr.new]p20:
992204643Srdivacky    //   If the lookup finds the two-parameter form of a usual
993204643Srdivacky    //   deallocation function (3.7.4.2) and that function, considered
994204643Srdivacky    //   as a placement deallocation function, would have been
995204643Srdivacky    //   selected as a match for the allocation function, the program
996204643Srdivacky    //   is ill-formed.
997204643Srdivacky    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
998204643Srdivacky        isNonPlacementDeallocationFunction(OperatorDelete)) {
999204643Srdivacky      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1000204643Srdivacky        << SourceRange(PlaceArgs[0]->getLocStart(),
1001204643Srdivacky                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1002204643Srdivacky      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1003204643Srdivacky        << DeleteName;
1004205408Srdivacky    } else {
1005205408Srdivacky      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1006205408Srdivacky                            Matches[0].first);
1007204643Srdivacky    }
1008204643Srdivacky  }
1009204643Srdivacky
1010193326Sed  return false;
1011193326Sed}
1012193326Sed
1013193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation
1014193326Sed/// function in the specified scope.
1015193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1016193326Sed                                  DeclarationName Name, Expr** Args,
1017193326Sed                                  unsigned NumArgs, DeclContext *Ctx,
1018198092Srdivacky                                  bool AllowMissing, FunctionDecl *&Operator) {
1019199482Srdivacky  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1020199482Srdivacky  LookupQualifiedName(R, Ctx);
1021198092Srdivacky  if (R.empty()) {
1022193326Sed    if (AllowMissing)
1023193326Sed      return false;
1024193326Sed    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1025193326Sed      << Name << Range;
1026193326Sed  }
1027193326Sed
1028205408Srdivacky  if (R.isAmbiguous())
1029205408Srdivacky    return true;
1030198092Srdivacky
1031205408Srdivacky  R.suppressDiagnostics();
1032205408Srdivacky
1033203955Srdivacky  OverloadCandidateSet Candidates(StartLoc);
1034198092Srdivacky  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1035198092Srdivacky       Alloc != AllocEnd; ++Alloc) {
1036193326Sed    // Even member operator new/delete are implicitly treated as
1037193326Sed    // static, so don't use AddMemberCandidate.
1038205408Srdivacky    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1039203955Srdivacky
1040205408Srdivacky    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1041205408Srdivacky      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1042203955Srdivacky                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1043203955Srdivacky                                   Candidates,
1044203955Srdivacky                                   /*SuppressUserConversions=*/false);
1045198092Srdivacky      continue;
1046203955Srdivacky    }
1047203955Srdivacky
1048205408Srdivacky    FunctionDecl *Fn = cast<FunctionDecl>(D);
1049205408Srdivacky    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1050203955Srdivacky                         /*SuppressUserConversions=*/false);
1051193326Sed  }
1052193326Sed
1053193326Sed  // Do the resolution.
1054193326Sed  OverloadCandidateSet::iterator Best;
1055194613Sed  switch(BestViableFunction(Candidates, StartLoc, Best)) {
1056193326Sed  case OR_Success: {
1057193326Sed    // Got one!
1058193326Sed    FunctionDecl *FnDecl = Best->Function;
1059193326Sed    // The first argument is size_t, and the first parameter must be size_t,
1060193326Sed    // too. This is checked on declaration and can be assumed. (It can't be
1061193326Sed    // asserted on, though, since invalid decls are left in there.)
1062205408Srdivacky    // Watch out for variadic allocator function.
1063199990Srdivacky    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1064199990Srdivacky    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1065193326Sed      if (PerformCopyInitialization(Args[i],
1066193326Sed                                    FnDecl->getParamDecl(i)->getType(),
1067201361Srdivacky                                    AA_Passing))
1068193326Sed        return true;
1069193326Sed    }
1070193326Sed    Operator = FnDecl;
1071205408Srdivacky    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1072193326Sed    return false;
1073193326Sed  }
1074193326Sed
1075193326Sed  case OR_No_Viable_Function:
1076193326Sed    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1077193326Sed      << Name << Range;
1078202379Srdivacky    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1079193326Sed    return true;
1080193326Sed
1081193326Sed  case OR_Ambiguous:
1082193326Sed    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1083193326Sed      << Name << Range;
1084202379Srdivacky    PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
1085193326Sed    return true;
1086193326Sed
1087193326Sed  case OR_Deleted:
1088193326Sed    Diag(StartLoc, diag::err_ovl_deleted_call)
1089193326Sed      << Best->Function->isDeleted()
1090193326Sed      << Name << Range;
1091202379Srdivacky    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1092193326Sed    return true;
1093193326Sed  }
1094193326Sed  assert(false && "Unreachable, bad result from BestViableFunction");
1095193326Sed  return true;
1096193326Sed}
1097193326Sed
1098193326Sed
1099193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1100193326Sed/// delete. These are:
1101193326Sed/// @code
1102193326Sed///   void* operator new(std::size_t) throw(std::bad_alloc);
1103193326Sed///   void* operator new[](std::size_t) throw(std::bad_alloc);
1104193326Sed///   void operator delete(void *) throw();
1105193326Sed///   void operator delete[](void *) throw();
1106193326Sed/// @endcode
1107193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly
1108193326Sed/// declared. Their use requires including \<new\>.
1109198092Srdivackyvoid Sema::DeclareGlobalNewDelete() {
1110193326Sed  if (GlobalNewDeleteDeclared)
1111193326Sed    return;
1112198092Srdivacky
1113198092Srdivacky  // C++ [basic.std.dynamic]p2:
1114198092Srdivacky  //   [...] The following allocation and deallocation functions (18.4) are
1115198092Srdivacky  //   implicitly declared in global scope in each translation unit of a
1116198092Srdivacky  //   program
1117198092Srdivacky  //
1118198092Srdivacky  //     void* operator new(std::size_t) throw(std::bad_alloc);
1119198092Srdivacky  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1120198092Srdivacky  //     void  operator delete(void*) throw();
1121198092Srdivacky  //     void  operator delete[](void*) throw();
1122198092Srdivacky  //
1123198092Srdivacky  //   These implicit declarations introduce only the function names operator
1124198092Srdivacky  //   new, operator new[], operator delete, operator delete[].
1125198092Srdivacky  //
1126198092Srdivacky  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1127198092Srdivacky  // "std" or "bad_alloc" as necessary to form the exception specification.
1128198092Srdivacky  // However, we do not make these implicit declarations visible to name
1129198092Srdivacky  // lookup.
1130198092Srdivacky  if (!StdNamespace) {
1131198092Srdivacky    // The "std" namespace has not yet been defined, so build one implicitly.
1132198092Srdivacky    StdNamespace = NamespaceDecl::Create(Context,
1133198092Srdivacky                                         Context.getTranslationUnitDecl(),
1134198092Srdivacky                                         SourceLocation(),
1135198092Srdivacky                                         &PP.getIdentifierTable().get("std"));
1136198092Srdivacky    StdNamespace->setImplicit(true);
1137198092Srdivacky  }
1138198092Srdivacky
1139198092Srdivacky  if (!StdBadAlloc) {
1140198092Srdivacky    // The "std::bad_alloc" class has not yet been declared, so build it
1141198092Srdivacky    // implicitly.
1142198092Srdivacky    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1143198092Srdivacky                                        StdNamespace,
1144198092Srdivacky                                        SourceLocation(),
1145198092Srdivacky                                      &PP.getIdentifierTable().get("bad_alloc"),
1146198092Srdivacky                                        SourceLocation(), 0);
1147198092Srdivacky    StdBadAlloc->setImplicit(true);
1148198092Srdivacky  }
1149198092Srdivacky
1150193326Sed  GlobalNewDeleteDeclared = true;
1151193326Sed
1152193326Sed  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1153193326Sed  QualType SizeT = Context.getSizeType();
1154201361Srdivacky  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1155193326Sed
1156193326Sed  DeclareGlobalAllocationFunction(
1157193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_New),
1158201361Srdivacky      VoidPtr, SizeT, AssumeSaneOperatorNew);
1159193326Sed  DeclareGlobalAllocationFunction(
1160193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1161201361Srdivacky      VoidPtr, SizeT, AssumeSaneOperatorNew);
1162193326Sed  DeclareGlobalAllocationFunction(
1163193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1164193326Sed      Context.VoidTy, VoidPtr);
1165193326Sed  DeclareGlobalAllocationFunction(
1166193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1167193326Sed      Context.VoidTy, VoidPtr);
1168193326Sed}
1169193326Sed
1170193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global
1171193326Sed/// allocation function if it doesn't already exist.
1172193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1173201361Srdivacky                                           QualType Return, QualType Argument,
1174201361Srdivacky                                           bool AddMallocAttr) {
1175193326Sed  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1176193326Sed
1177193326Sed  // Check if this function is already declared.
1178193326Sed  {
1179193326Sed    DeclContext::lookup_iterator Alloc, AllocEnd;
1180195341Sed    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1181193326Sed         Alloc != AllocEnd; ++Alloc) {
1182203955Srdivacky      // Only look at non-template functions, as it is the predefined,
1183203955Srdivacky      // non-templated allocation function we are trying to declare here.
1184203955Srdivacky      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1185203955Srdivacky        QualType InitialParamType =
1186201361Srdivacky          Context.getCanonicalType(
1187203955Srdivacky            Func->getParamDecl(0)->getType().getUnqualifiedType());
1188203955Srdivacky        // FIXME: Do we need to check for default arguments here?
1189203955Srdivacky        if (Func->getNumParams() == 1 && InitialParamType == Argument)
1190203955Srdivacky          return;
1191203955Srdivacky      }
1192193326Sed    }
1193193326Sed  }
1194193326Sed
1195198092Srdivacky  QualType BadAllocType;
1196198092Srdivacky  bool HasBadAllocExceptionSpec
1197198092Srdivacky    = (Name.getCXXOverloadedOperator() == OO_New ||
1198198092Srdivacky       Name.getCXXOverloadedOperator() == OO_Array_New);
1199198092Srdivacky  if (HasBadAllocExceptionSpec) {
1200198092Srdivacky    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1201198092Srdivacky    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1202198092Srdivacky  }
1203198092Srdivacky
1204198092Srdivacky  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1205198092Srdivacky                                            true, false,
1206198092Srdivacky                                            HasBadAllocExceptionSpec? 1 : 0,
1207204643Srdivacky                                            &BadAllocType, false, CC_Default);
1208193326Sed  FunctionDecl *Alloc =
1209193326Sed    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1210200583Srdivacky                         FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
1211193326Sed  Alloc->setImplicit();
1212201361Srdivacky
1213201361Srdivacky  if (AddMallocAttr)
1214201361Srdivacky    Alloc->addAttr(::new (Context) MallocAttr());
1215201361Srdivacky
1216193326Sed  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1217200583Srdivacky                                           0, Argument, /*TInfo=*/0,
1218198092Srdivacky                                           VarDecl::None, 0);
1219203955Srdivacky  Alloc->setParams(&Param, 1);
1220193326Sed
1221193326Sed  // FIXME: Also add this declaration to the IdentifierResolver, but
1222193326Sed  // make sure it is at the end of the chain to coincide with the
1223193326Sed  // global scope.
1224195341Sed  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
1225193326Sed}
1226193326Sed
1227199482Srdivackybool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1228199482Srdivacky                                    DeclarationName Name,
1229199482Srdivacky                                    FunctionDecl* &Operator) {
1230199482Srdivacky  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1231199482Srdivacky  // Try to find operator delete/operator delete[] in class scope.
1232199482Srdivacky  LookupQualifiedName(Found, RD);
1233199482Srdivacky
1234199482Srdivacky  if (Found.isAmbiguous())
1235199482Srdivacky    return true;
1236199482Srdivacky
1237199482Srdivacky  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1238199482Srdivacky       F != FEnd; ++F) {
1239199482Srdivacky    if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1240199482Srdivacky      if (Delete->isUsualDeallocationFunction()) {
1241199482Srdivacky        Operator = Delete;
1242199482Srdivacky        return false;
1243199482Srdivacky      }
1244199482Srdivacky  }
1245199482Srdivacky
1246199482Srdivacky  // We did find operator delete/operator delete[] declarations, but
1247199482Srdivacky  // none of them were suitable.
1248199482Srdivacky  if (!Found.empty()) {
1249199482Srdivacky    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1250199482Srdivacky      << Name << RD;
1251199482Srdivacky
1252199482Srdivacky    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1253199482Srdivacky         F != FEnd; ++F) {
1254199482Srdivacky      Diag((*F)->getLocation(),
1255199482Srdivacky           diag::note_delete_member_function_declared_here)
1256199482Srdivacky        << Name;
1257199482Srdivacky    }
1258199482Srdivacky
1259199482Srdivacky    return true;
1260199482Srdivacky  }
1261199482Srdivacky
1262199482Srdivacky  // Look for a global declaration.
1263199482Srdivacky  DeclareGlobalNewDelete();
1264199482Srdivacky  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1265199482Srdivacky
1266199482Srdivacky  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1267199482Srdivacky  Expr* DeallocArgs[1];
1268199482Srdivacky  DeallocArgs[0] = &Null;
1269199482Srdivacky  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1270199482Srdivacky                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1271199482Srdivacky                             Operator))
1272199482Srdivacky    return true;
1273199482Srdivacky
1274199482Srdivacky  assert(Operator && "Did not find a deallocation function!");
1275199482Srdivacky  return false;
1276199482Srdivacky}
1277199482Srdivacky
1278193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1279193326Sed/// @code ::delete ptr; @endcode
1280193326Sed/// or
1281193326Sed/// @code delete [] ptr; @endcode
1282193326SedAction::OwningExprResult
1283193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1284198092Srdivacky                     bool ArrayForm, ExprArg Operand) {
1285198092Srdivacky  // C++ [expr.delete]p1:
1286198092Srdivacky  //   The operand shall have a pointer type, or a class type having a single
1287198092Srdivacky  //   conversion function to a pointer type. The result has type void.
1288198092Srdivacky  //
1289193326Sed  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1290193326Sed
1291198092Srdivacky  FunctionDecl *OperatorDelete = 0;
1292198092Srdivacky
1293193326Sed  Expr *Ex = (Expr *)Operand.get();
1294193326Sed  if (!Ex->isTypeDependent()) {
1295193326Sed    QualType Type = Ex->getType();
1296193326Sed
1297198092Srdivacky    if (const RecordType *Record = Type->getAs<RecordType>()) {
1298198092Srdivacky      llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
1299198092Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1300202879Srdivacky      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1301198092Srdivacky
1302202879Srdivacky      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1303199990Srdivacky             E = Conversions->end(); I != E; ++I) {
1304198092Srdivacky        // Skip over templated conversion functions; they aren't considered.
1305199990Srdivacky        if (isa<FunctionTemplateDecl>(*I))
1306198092Srdivacky          continue;
1307198092Srdivacky
1308199990Srdivacky        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
1309198092Srdivacky
1310198092Srdivacky        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1311198092Srdivacky        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1312198092Srdivacky          if (ConvPtrType->getPointeeType()->isObjectType())
1313198092Srdivacky            ObjectPtrConversions.push_back(Conv);
1314198092Srdivacky      }
1315198092Srdivacky      if (ObjectPtrConversions.size() == 1) {
1316198092Srdivacky        // We have a single conversion to a pointer-to-object type. Perform
1317198092Srdivacky        // that conversion.
1318198092Srdivacky        Operand.release();
1319198092Srdivacky        if (!PerformImplicitConversion(Ex,
1320198092Srdivacky                            ObjectPtrConversions.front()->getConversionType(),
1321201361Srdivacky                                      AA_Converting)) {
1322198092Srdivacky          Operand = Owned(Ex);
1323198092Srdivacky          Type = Ex->getType();
1324198092Srdivacky        }
1325198092Srdivacky      }
1326198092Srdivacky      else if (ObjectPtrConversions.size() > 1) {
1327198092Srdivacky        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1328198092Srdivacky              << Type << Ex->getSourceRange();
1329198092Srdivacky        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1330198092Srdivacky          CXXConversionDecl *Conv = ObjectPtrConversions[i];
1331202379Srdivacky          NoteOverloadCandidate(Conv);
1332198092Srdivacky        }
1333198092Srdivacky        return ExprError();
1334198092Srdivacky      }
1335193326Sed    }
1336193326Sed
1337193326Sed    if (!Type->isPointerType())
1338193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1339193326Sed        << Type << Ex->getSourceRange());
1340193326Sed
1341198092Srdivacky    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1342193326Sed    if (Pointee->isFunctionType() || Pointee->isVoidType())
1343193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1344193326Sed        << Type << Ex->getSourceRange());
1345193326Sed    else if (!Pointee->isDependentType() &&
1346198092Srdivacky             RequireCompleteType(StartLoc, Pointee,
1347198092Srdivacky                                 PDiag(diag::warn_delete_incomplete)
1348198092Srdivacky                                   << Ex->getSourceRange()))
1349193326Sed      return ExprError();
1350193326Sed
1351198092Srdivacky    // C++ [expr.delete]p2:
1352198092Srdivacky    //   [Note: a pointer to a const type can be the operand of a
1353198092Srdivacky    //   delete-expression; it is not necessary to cast away the constness
1354198092Srdivacky    //   (5.2.11) of the pointer expression before it is used as the operand
1355198092Srdivacky    //   of the delete-expression. ]
1356198092Srdivacky    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1357198092Srdivacky                      CastExpr::CK_NoOp);
1358198092Srdivacky
1359198092Srdivacky    // Update the operand.
1360198092Srdivacky    Operand.take();
1361198092Srdivacky    Operand = ExprArg(*this, Ex);
1362198092Srdivacky
1363198092Srdivacky    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1364198092Srdivacky                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1365198092Srdivacky
1366199482Srdivacky    if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1367199482Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1368199482Srdivacky
1369199482Srdivacky      if (!UseGlobal &&
1370199482Srdivacky          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1371199482Srdivacky        return ExprError();
1372198092Srdivacky
1373199482Srdivacky      if (!RD->hasTrivialDestructor())
1374199482Srdivacky        if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
1375198092Srdivacky          MarkDeclarationReferenced(StartLoc,
1376198092Srdivacky                                    const_cast<CXXDestructorDecl*>(Dtor));
1377198092Srdivacky    }
1378199482Srdivacky
1379198092Srdivacky    if (!OperatorDelete) {
1380199482Srdivacky      // Look for a global declaration.
1381198092Srdivacky      DeclareGlobalNewDelete();
1382198092Srdivacky      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1383198092Srdivacky      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1384198092Srdivacky                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1385198092Srdivacky                                 OperatorDelete))
1386198092Srdivacky        return ExprError();
1387198092Srdivacky    }
1388198092Srdivacky
1389193326Sed    // FIXME: Check access and ambiguity of operator delete and destructor.
1390193326Sed  }
1391193326Sed
1392193326Sed  Operand.release();
1393193326Sed  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1394198092Srdivacky                                           OperatorDelete, Ex, StartLoc));
1395193326Sed}
1396193326Sed
1397199990Srdivacky/// \brief Check the use of the given variable as a C++ condition in an if,
1398199990Srdivacky/// while, do-while, or switch statement.
1399199990SrdivackyAction::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1400199990Srdivacky  QualType T = ConditionVar->getType();
1401199990Srdivacky
1402199990Srdivacky  // C++ [stmt.select]p2:
1403199990Srdivacky  //   The declarator shall not specify a function or an array.
1404199990Srdivacky  if (T->isFunctionType())
1405199990Srdivacky    return ExprError(Diag(ConditionVar->getLocation(),
1406199990Srdivacky                          diag::err_invalid_use_of_function_type)
1407199990Srdivacky                       << ConditionVar->getSourceRange());
1408199990Srdivacky  else if (T->isArrayType())
1409199990Srdivacky    return ExprError(Diag(ConditionVar->getLocation(),
1410199990Srdivacky                          diag::err_invalid_use_of_array_type)
1411199990Srdivacky                     << ConditionVar->getSourceRange());
1412193326Sed
1413199990Srdivacky  return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1414199990Srdivacky                                   ConditionVar->getLocation(),
1415199990Srdivacky                                ConditionVar->getType().getNonReferenceType()));
1416193326Sed}
1417193326Sed
1418193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1419193326Sedbool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1420193326Sed  // C++ 6.4p4:
1421193326Sed  // The value of a condition that is an initialized declaration in a statement
1422193326Sed  // other than a switch statement is the value of the declared variable
1423193326Sed  // implicitly converted to type bool. If that conversion is ill-formed, the
1424193326Sed  // program is ill-formed.
1425193326Sed  // The value of a condition that is an expression is the value of the
1426193326Sed  // expression, implicitly converted to bool.
1427193326Sed  //
1428193326Sed  return PerformContextuallyConvertToBool(CondExpr);
1429193326Sed}
1430193326Sed
1431193326Sed/// Helper function to determine whether this is the (deprecated) C++
1432193326Sed/// conversion from a string literal to a pointer to non-const char or
1433193326Sed/// non-const wchar_t (for narrow and wide string literals,
1434193326Sed/// respectively).
1435198092Srdivackybool
1436193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1437193326Sed  // Look inside the implicit cast, if it exists.
1438193326Sed  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1439193326Sed    From = Cast->getSubExpr();
1440193326Sed
1441193326Sed  // A string literal (2.13.4) that is not a wide string literal can
1442193326Sed  // be converted to an rvalue of type "pointer to char"; a wide
1443193326Sed  // string literal can be converted to an rvalue of type "pointer
1444193326Sed  // to wchar_t" (C++ 4.2p2).
1445193326Sed  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
1446198092Srdivacky    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1447198092Srdivacky      if (const BuiltinType *ToPointeeType
1448198092Srdivacky          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1449193326Sed        // This conversion is considered only when there is an
1450193326Sed        // explicit appropriate pointer target type (C++ 4.2p2).
1451198092Srdivacky        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1452193326Sed            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1453193326Sed             (!StrLit->isWide() &&
1454193326Sed              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1455193326Sed               ToPointeeType->getKind() == BuiltinType::Char_S))))
1456193326Sed          return true;
1457193326Sed      }
1458193326Sed
1459193326Sed  return false;
1460193326Sed}
1461193326Sed
1462193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1463193326Sed/// expression From to the type ToType. Returns true if there was an
1464193326Sed/// error, false otherwise. The expression From is replaced with the
1465193326Sed/// converted expression. Flavor is the kind of conversion we're
1466193326Sed/// performing, used in the error message. If @p AllowExplicit,
1467193326Sed/// explicit user-defined conversions are permitted. @p Elidable should be true
1468193326Sed/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1469193326Sed/// resolution works differently in that case.
1470193326Sedbool
1471193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1472201361Srdivacky                                AssignmentAction Action, bool AllowExplicit,
1473198092Srdivacky                                bool Elidable) {
1474193326Sed  ImplicitConversionSequence ICS;
1475201361Srdivacky  return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
1476198092Srdivacky                                   Elidable, ICS);
1477198092Srdivacky}
1478198092Srdivacky
1479198092Srdivackybool
1480198092SrdivackySema::PerformImplicitConversion(Expr *&From, QualType ToType,
1481201361Srdivacky                                AssignmentAction Action, bool AllowExplicit,
1482198092Srdivacky                                bool Elidable,
1483198092Srdivacky                                ImplicitConversionSequence& ICS) {
1484204643Srdivacky  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1485193326Sed  if (Elidable && getLangOptions().CPlusPlus0x) {
1486198092Srdivacky    ICS = TryImplicitConversion(From, ToType,
1487198092Srdivacky                                /*SuppressUserConversions=*/false,
1488198092Srdivacky                                AllowExplicit,
1489198092Srdivacky                                /*ForceRValue=*/true,
1490198092Srdivacky                                /*InOverloadResolution=*/false);
1491193326Sed  }
1492202379Srdivacky  if (ICS.isBad()) {
1493198092Srdivacky    ICS = TryImplicitConversion(From, ToType,
1494198092Srdivacky                                /*SuppressUserConversions=*/false,
1495198092Srdivacky                                AllowExplicit,
1496198092Srdivacky                                /*ForceRValue=*/false,
1497198092Srdivacky                                /*InOverloadResolution=*/false);
1498193326Sed  }
1499201361Srdivacky  return PerformImplicitConversion(From, ToType, ICS, Action);
1500193326Sed}
1501193326Sed
1502193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1503193326Sed/// expression From to the type ToType using the pre-computed implicit
1504193326Sed/// conversion sequence ICS. Returns true if there was an error, false
1505193326Sed/// otherwise. The expression From is replaced with the converted
1506201361Srdivacky/// expression. Action is the kind of conversion we're performing,
1507193326Sed/// used in the error message.
1508193326Sedbool
1509193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1510193326Sed                                const ImplicitConversionSequence &ICS,
1511201361Srdivacky                                AssignmentAction Action, bool IgnoreBaseAccess) {
1512202379Srdivacky  switch (ICS.getKind()) {
1513193326Sed  case ImplicitConversionSequence::StandardConversion:
1514201361Srdivacky    if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1515199482Srdivacky                                  IgnoreBaseAccess))
1516193326Sed      return true;
1517193326Sed    break;
1518193326Sed
1519198092Srdivacky  case ImplicitConversionSequence::UserDefinedConversion: {
1520198092Srdivacky
1521198092Srdivacky      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1522198092Srdivacky      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1523198092Srdivacky      QualType BeforeToType;
1524198092Srdivacky      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1525198092Srdivacky        CastKind = CastExpr::CK_UserDefinedConversion;
1526198092Srdivacky
1527198092Srdivacky        // If the user-defined conversion is specified by a conversion function,
1528198092Srdivacky        // the initial standard conversion sequence converts the source type to
1529198092Srdivacky        // the implicit object parameter of the conversion function.
1530198092Srdivacky        BeforeToType = Context.getTagDeclType(Conv->getParent());
1531198092Srdivacky      } else if (const CXXConstructorDecl *Ctor =
1532198092Srdivacky                  dyn_cast<CXXConstructorDecl>(FD)) {
1533198092Srdivacky        CastKind = CastExpr::CK_ConstructorConversion;
1534199482Srdivacky        // Do no conversion if dealing with ... for the first conversion.
1535199990Srdivacky        if (!ICS.UserDefined.EllipsisConversion) {
1536199482Srdivacky          // If the user-defined conversion is specified by a constructor, the
1537199482Srdivacky          // initial standard conversion sequence converts the source type to the
1538199482Srdivacky          // type required by the argument of the constructor
1539199990Srdivacky          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1540199990Srdivacky        }
1541198092Srdivacky      }
1542198092Srdivacky      else
1543198092Srdivacky        assert(0 && "Unknown conversion function kind!");
1544199482Srdivacky      // Whatch out for elipsis conversion.
1545199482Srdivacky      if (!ICS.UserDefined.EllipsisConversion) {
1546199482Srdivacky        if (PerformImplicitConversion(From, BeforeToType,
1547201361Srdivacky                                      ICS.UserDefined.Before, AA_Converting,
1548199482Srdivacky                                      IgnoreBaseAccess))
1549199482Srdivacky          return true;
1550199482Srdivacky      }
1551198092Srdivacky
1552198092Srdivacky      OwningExprResult CastArg
1553198092Srdivacky        = BuildCXXCastArgument(From->getLocStart(),
1554198092Srdivacky                               ToType.getNonReferenceType(),
1555198092Srdivacky                               CastKind, cast<CXXMethodDecl>(FD),
1556198092Srdivacky                               Owned(From));
1557198092Srdivacky
1558198092Srdivacky      if (CastArg.isInvalid())
1559198092Srdivacky        return true;
1560199990Srdivacky
1561199990Srdivacky      From = CastArg.takeAs<Expr>();
1562199990Srdivacky
1563199990Srdivacky      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1564201361Srdivacky                                       AA_Converting, IgnoreBaseAccess);
1565198398Srdivacky  }
1566202379Srdivacky
1567202379Srdivacky  case ImplicitConversionSequence::AmbiguousConversion:
1568202379Srdivacky    DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1569202379Srdivacky                          PDiag(diag::err_typecheck_ambiguous_condition)
1570202379Srdivacky                            << From->getSourceRange());
1571202379Srdivacky     return true;
1572198398Srdivacky
1573193326Sed  case ImplicitConversionSequence::EllipsisConversion:
1574193326Sed    assert(false && "Cannot perform an ellipsis conversion");
1575193326Sed    return false;
1576193326Sed
1577193326Sed  case ImplicitConversionSequence::BadConversion:
1578193326Sed    return true;
1579193326Sed  }
1580193326Sed
1581193326Sed  // Everything went well.
1582193326Sed  return false;
1583193326Sed}
1584193326Sed
1585193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1586193326Sed/// expression From to the type ToType by following the standard
1587193326Sed/// conversion sequence SCS. Returns true if there was an error, false
1588193326Sed/// otherwise. The expression From is replaced with the converted
1589193326Sed/// expression. Flavor is the context in which we're performing this
1590193326Sed/// conversion, for use in error messages.
1591198092Srdivackybool
1592193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1593193326Sed                                const StandardConversionSequence& SCS,
1594201361Srdivacky                                AssignmentAction Action, bool IgnoreBaseAccess) {
1595193326Sed  // Overall FIXME: we are recomputing too many types here and doing far too
1596193326Sed  // much extra work. What this means is that we need to keep track of more
1597193326Sed  // information that is computed when we try the implicit conversion initially,
1598193326Sed  // so that we don't need to recompute anything here.
1599193326Sed  QualType FromType = From->getType();
1600193326Sed
1601193326Sed  if (SCS.CopyConstructor) {
1602193326Sed    // FIXME: When can ToType be a reference type?
1603193326Sed    assert(!ToType->isReferenceType());
1604198092Srdivacky    if (SCS.Second == ICK_Derived_To_Base) {
1605198092Srdivacky      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1606198092Srdivacky      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1607198092Srdivacky                                  MultiExprArg(*this, (void **)&From, 1),
1608198092Srdivacky                                  /*FIXME:ConstructLoc*/SourceLocation(),
1609198092Srdivacky                                  ConstructorArgs))
1610198092Srdivacky        return true;
1611198092Srdivacky      OwningExprResult FromResult =
1612198092Srdivacky        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1613198092Srdivacky                              ToType, SCS.CopyConstructor,
1614198092Srdivacky                              move_arg(ConstructorArgs));
1615198092Srdivacky      if (FromResult.isInvalid())
1616198092Srdivacky        return true;
1617198092Srdivacky      From = FromResult.takeAs<Expr>();
1618198092Srdivacky      return false;
1619198092Srdivacky    }
1620198092Srdivacky    OwningExprResult FromResult =
1621198092Srdivacky      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1622198092Srdivacky                            ToType, SCS.CopyConstructor,
1623198092Srdivacky                            MultiExprArg(*this, (void**)&From, 1));
1624198092Srdivacky
1625198092Srdivacky    if (FromResult.isInvalid())
1626198092Srdivacky      return true;
1627198092Srdivacky
1628198092Srdivacky    From = FromResult.takeAs<Expr>();
1629193326Sed    return false;
1630193326Sed  }
1631193326Sed
1632193326Sed  // Perform the first implicit conversion.
1633193326Sed  switch (SCS.First) {
1634193326Sed  case ICK_Identity:
1635193326Sed  case ICK_Lvalue_To_Rvalue:
1636193326Sed    // Nothing to do.
1637193326Sed    break;
1638193326Sed
1639193326Sed  case ICK_Array_To_Pointer:
1640193326Sed    FromType = Context.getArrayDecayedType(FromType);
1641198092Srdivacky    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1642193326Sed    break;
1643193326Sed
1644193326Sed  case ICK_Function_To_Pointer:
1645193326Sed    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1646193326Sed      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1647193326Sed      if (!Fn)
1648193326Sed        return true;
1649193326Sed
1650193326Sed      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1651193326Sed        return true;
1652193326Sed
1653198398Srdivacky      From = FixOverloadedFunctionReference(From, Fn);
1654193326Sed      FromType = From->getType();
1655198398Srdivacky
1656198398Srdivacky      // If there's already an address-of operator in the expression, we have
1657198398Srdivacky      // the right type already, and the code below would just introduce an
1658198398Srdivacky      // invalid additional pointer level.
1659198398Srdivacky      if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
1660198398Srdivacky        break;
1661193326Sed    }
1662193326Sed    FromType = Context.getPointerType(FromType);
1663198092Srdivacky    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1664193326Sed    break;
1665193326Sed
1666193326Sed  default:
1667193326Sed    assert(false && "Improper first standard conversion");
1668193326Sed    break;
1669193326Sed  }
1670193326Sed
1671193326Sed  // Perform the second implicit conversion
1672193326Sed  switch (SCS.Second) {
1673193326Sed  case ICK_Identity:
1674198092Srdivacky    // If both sides are functions (or pointers/references to them), there could
1675198092Srdivacky    // be incompatible exception declarations.
1676198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
1677198092Srdivacky      return true;
1678198092Srdivacky    // Nothing else to do.
1679193326Sed    break;
1680193326Sed
1681200583Srdivacky  case ICK_NoReturn_Adjustment:
1682200583Srdivacky    // If both sides are functions (or pointers/references to them), there could
1683200583Srdivacky    // be incompatible exception declarations.
1684200583Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
1685200583Srdivacky      return true;
1686200583Srdivacky
1687200583Srdivacky    ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1688200583Srdivacky                      CastExpr::CK_NoOp);
1689200583Srdivacky    break;
1690200583Srdivacky
1691193326Sed  case ICK_Integral_Promotion:
1692198398Srdivacky  case ICK_Integral_Conversion:
1693198398Srdivacky    ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1694198398Srdivacky    break;
1695198398Srdivacky
1696193326Sed  case ICK_Floating_Promotion:
1697198398Srdivacky  case ICK_Floating_Conversion:
1698198398Srdivacky    ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1699198398Srdivacky    break;
1700198398Srdivacky
1701193326Sed  case ICK_Complex_Promotion:
1702193326Sed  case ICK_Complex_Conversion:
1703198398Srdivacky    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1704198398Srdivacky    break;
1705198398Srdivacky
1706193326Sed  case ICK_Floating_Integral:
1707198398Srdivacky    if (ToType->isFloatingType())
1708198398Srdivacky      ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1709198398Srdivacky    else
1710198398Srdivacky      ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1711198398Srdivacky    break;
1712198398Srdivacky
1713193326Sed  case ICK_Complex_Real:
1714198398Srdivacky    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1715198398Srdivacky    break;
1716198398Srdivacky
1717193326Sed  case ICK_Compatible_Conversion:
1718198398Srdivacky    ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
1719193326Sed    break;
1720193326Sed
1721198092Srdivacky  case ICK_Pointer_Conversion: {
1722193326Sed    if (SCS.IncompatibleObjC) {
1723193326Sed      // Diagnose incompatible Objective-C conversions
1724198092Srdivacky      Diag(From->getSourceRange().getBegin(),
1725193326Sed           diag::ext_typecheck_convert_incompatible_pointer)
1726201361Srdivacky        << From->getType() << ToType << Action
1727193326Sed        << From->getSourceRange();
1728193326Sed    }
1729193326Sed
1730198092Srdivacky
1731198092Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1732199482Srdivacky    if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
1733193326Sed      return true;
1734198092Srdivacky    ImpCastExprToType(From, ToType, Kind);
1735193326Sed    break;
1736198092Srdivacky  }
1737198092Srdivacky
1738198092Srdivacky  case ICK_Pointer_Member: {
1739198092Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1740199482Srdivacky    if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
1741193326Sed      return true;
1742198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
1743198092Srdivacky      return true;
1744198092Srdivacky    ImpCastExprToType(From, ToType, Kind);
1745193326Sed    break;
1746198092Srdivacky  }
1747199990Srdivacky  case ICK_Boolean_Conversion: {
1748199990Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1749199990Srdivacky    if (FromType->isMemberPointerType())
1750199990Srdivacky      Kind = CastExpr::CK_MemberPointerToBoolean;
1751199990Srdivacky
1752199990Srdivacky    ImpCastExprToType(From, Context.BoolTy, Kind);
1753193326Sed    break;
1754199990Srdivacky  }
1755193326Sed
1756199482Srdivacky  case ICK_Derived_To_Base:
1757199482Srdivacky    if (CheckDerivedToBaseConversion(From->getType(),
1758199482Srdivacky                                     ToType.getNonReferenceType(),
1759199482Srdivacky                                     From->getLocStart(),
1760199482Srdivacky                                     From->getSourceRange(),
1761199482Srdivacky                                     IgnoreBaseAccess))
1762199482Srdivacky      return true;
1763199482Srdivacky    ImpCastExprToType(From, ToType.getNonReferenceType(),
1764199482Srdivacky                      CastExpr::CK_DerivedToBase);
1765199482Srdivacky    break;
1766199482Srdivacky
1767193326Sed  default:
1768193326Sed    assert(false && "Improper second standard conversion");
1769193326Sed    break;
1770193326Sed  }
1771193326Sed
1772193326Sed  switch (SCS.Third) {
1773193326Sed  case ICK_Identity:
1774193326Sed    // Nothing to do.
1775193326Sed    break;
1776193326Sed
1777193326Sed  case ICK_Qualification:
1778193326Sed    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1779193326Sed    // references.
1780198092Srdivacky    ImpCastExprToType(From, ToType.getNonReferenceType(),
1781198398Srdivacky                      CastExpr::CK_NoOp,
1782193326Sed                      ToType->isLValueReferenceType());
1783204643Srdivacky
1784204643Srdivacky    if (SCS.DeprecatedStringLiteralToCharPtr)
1785204643Srdivacky      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1786204643Srdivacky        << ToType.getNonReferenceType();
1787204643Srdivacky
1788193326Sed    break;
1789199482Srdivacky
1790193326Sed  default:
1791193326Sed    assert(false && "Improper second standard conversion");
1792193326Sed    break;
1793193326Sed  }
1794193326Sed
1795193326Sed  return false;
1796193326Sed}
1797193326Sed
1798193326SedSema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1799193326Sed                                                 SourceLocation KWLoc,
1800193326Sed                                                 SourceLocation LParen,
1801193326Sed                                                 TypeTy *Ty,
1802193326Sed                                                 SourceLocation RParen) {
1803198092Srdivacky  QualType T = GetTypeFromParser(Ty);
1804193326Sed
1805198092Srdivacky  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1806198092Srdivacky  // all traits except __is_class, __is_enum and __is_union require a the type
1807198092Srdivacky  // to be complete.
1808198092Srdivacky  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1809198092Srdivacky    if (RequireCompleteType(KWLoc, T,
1810198092Srdivacky                            diag::err_incomplete_type_used_in_type_trait_expr))
1811198092Srdivacky      return ExprError();
1812198092Srdivacky  }
1813198092Srdivacky
1814193326Sed  // There is no point in eagerly computing the value. The traits are designed
1815193326Sed  // to be used from type trait templates, so Ty will be a template parameter
1816193326Sed  // 99% of the time.
1817198092Srdivacky  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1818198092Srdivacky                                                RParen, Context.BoolTy));
1819193326Sed}
1820193326Sed
1821193326SedQualType Sema::CheckPointerToMemberOperands(
1822198092Srdivacky  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1823193326Sed  const char *OpSpelling = isIndirect ? "->*" : ".*";
1824193326Sed  // C++ 5.5p2
1825193326Sed  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1826193326Sed  //   be of type "pointer to member of T" (where T is a completely-defined
1827193326Sed  //   class type) [...]
1828193326Sed  QualType RType = rex->getType();
1829198092Srdivacky  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1830193326Sed  if (!MemPtr) {
1831193326Sed    Diag(Loc, diag::err_bad_memptr_rhs)
1832193326Sed      << OpSpelling << RType << rex->getSourceRange();
1833193326Sed    return QualType();
1834198092Srdivacky  }
1835193326Sed
1836193326Sed  QualType Class(MemPtr->getClass(), 0);
1837193326Sed
1838193326Sed  // C++ 5.5p2
1839193326Sed  //   [...] to its first operand, which shall be of class T or of a class of
1840193326Sed  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1841193326Sed  //   such a class]
1842193326Sed  QualType LType = lex->getType();
1843193326Sed  if (isIndirect) {
1844198092Srdivacky    if (const PointerType *Ptr = LType->getAs<PointerType>())
1845193326Sed      LType = Ptr->getPointeeType().getNonReferenceType();
1846193326Sed    else {
1847193326Sed      Diag(Loc, diag::err_bad_memptr_lhs)
1848198893Srdivacky        << OpSpelling << 1 << LType
1849198893Srdivacky        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
1850193326Sed      return QualType();
1851193326Sed    }
1852193326Sed  }
1853193326Sed
1854199482Srdivacky  if (!Context.hasSameUnqualifiedType(Class, LType)) {
1855198092Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1856198092Srdivacky                       /*DetectVirtual=*/false);
1857193326Sed    // FIXME: Would it be useful to print full ambiguity paths, or is that
1858193326Sed    // overkill?
1859193326Sed    if (!IsDerivedFrom(LType, Class, Paths) ||
1860193326Sed        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1861193326Sed      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1862202879Srdivacky        << (int)isIndirect << lex->getType();
1863193326Sed      return QualType();
1864193326Sed    }
1865202879Srdivacky    // Cast LHS to type of use.
1866202879Srdivacky    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1867202879Srdivacky    bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1868202879Srdivacky    ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
1869193326Sed  }
1870193326Sed
1871199512Srdivacky  if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
1872199512Srdivacky    // Diagnose use of pointer-to-member type which when used as
1873199512Srdivacky    // the functional cast in a pointer-to-member expression.
1874199512Srdivacky    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1875199512Srdivacky     return QualType();
1876199512Srdivacky  }
1877193326Sed  // C++ 5.5p2
1878193326Sed  //   The result is an object or a function of the type specified by the
1879193326Sed  //   second operand.
1880193326Sed  // The cv qualifiers are the union of those in the pointer and the left side,
1881193326Sed  // in accordance with 5.5p5 and 5.2.5.
1882193326Sed  // FIXME: This returns a dereferenced member function pointer as a normal
1883193326Sed  // function type. However, the only operation valid on such functions is
1884193326Sed  // calling them. There's also a GCC extension to get a function pointer to the
1885193326Sed  // thing, which is another complication, because this type - unlike the type
1886193326Sed  // that is the result of this expression - takes the class as the first
1887193326Sed  // argument.
1888193326Sed  // We probably need a "MemberFunctionClosureType" or something like that.
1889193326Sed  QualType Result = MemPtr->getPointeeType();
1890198092Srdivacky  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1891193326Sed  return Result;
1892193326Sed}
1893193326Sed
1894193326Sed/// \brief Get the target type of a standard or user-defined conversion.
1895193326Sedstatic QualType TargetType(const ImplicitConversionSequence &ICS) {
1896202379Srdivacky  switch (ICS.getKind()) {
1897202379Srdivacky  case ImplicitConversionSequence::StandardConversion:
1898203955Srdivacky    return ICS.Standard.getToType(2);
1899202379Srdivacky  case ImplicitConversionSequence::UserDefinedConversion:
1900203955Srdivacky    return ICS.UserDefined.After.getToType(2);
1901202379Srdivacky  case ImplicitConversionSequence::AmbiguousConversion:
1902202379Srdivacky    return ICS.Ambiguous.getToType();
1903204643Srdivacky
1904202379Srdivacky  case ImplicitConversionSequence::EllipsisConversion:
1905202379Srdivacky  case ImplicitConversionSequence::BadConversion:
1906202379Srdivacky    llvm_unreachable("function not valid for ellipsis or bad conversions");
1907202379Srdivacky  }
1908202379Srdivacky  return QualType(); // silence warnings
1909193326Sed}
1910193326Sed
1911193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3.
1912193326Sed///
1913193326Sed/// This is part of the parameter validation for the ? operator. If either
1914193326Sed/// value operand is a class type, the two operands are attempted to be
1915193326Sed/// converted to each other. This function does the conversion in one direction.
1916193326Sed/// It emits a diagnostic and returns true only if it finds an ambiguous
1917193326Sed/// conversion.
1918193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1919193326Sed                                SourceLocation QuestionLoc,
1920198092Srdivacky                                ImplicitConversionSequence &ICS) {
1921193326Sed  // C++0x 5.16p3
1922193326Sed  //   The process for determining whether an operand expression E1 of type T1
1923193326Sed  //   can be converted to match an operand expression E2 of type T2 is defined
1924193326Sed  //   as follows:
1925193326Sed  //   -- If E2 is an lvalue:
1926193326Sed  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1927193326Sed    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1928193326Sed    //   type "lvalue reference to T2", subject to the constraint that in the
1929193326Sed    //   conversion the reference must bind directly to E1.
1930193326Sed    if (!Self.CheckReferenceInit(From,
1931193326Sed                            Self.Context.getLValueReferenceType(To->getType()),
1932198092Srdivacky                                 To->getLocStart(),
1933198092Srdivacky                                 /*SuppressUserConversions=*/false,
1934198092Srdivacky                                 /*AllowExplicit=*/false,
1935198092Srdivacky                                 /*ForceRValue=*/false,
1936198092Srdivacky                                 &ICS))
1937193326Sed    {
1938202379Srdivacky      assert((ICS.isStandard() || ICS.isUserDefined()) &&
1939193326Sed             "expected a definite conversion");
1940193326Sed      bool DirectBinding =
1941202379Srdivacky        ICS.isStandard() ? ICS.Standard.DirectBinding
1942202379Srdivacky                         : ICS.UserDefined.After.DirectBinding;
1943193326Sed      if (DirectBinding)
1944193326Sed        return false;
1945193326Sed    }
1946193326Sed  }
1947204643Srdivacky
1948193326Sed  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1949193326Sed  //      -- if E1 and E2 have class type, and the underlying class types are
1950193326Sed  //         the same or one is a base class of the other:
1951193326Sed  QualType FTy = From->getType();
1952193326Sed  QualType TTy = To->getType();
1953198092Srdivacky  const RecordType *FRec = FTy->getAs<RecordType>();
1954198092Srdivacky  const RecordType *TRec = TTy->getAs<RecordType>();
1955193326Sed  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1956193326Sed  if (FRec && TRec && (FRec == TRec ||
1957193326Sed        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1958193326Sed    //         E1 can be converted to match E2 if the class of T2 is the
1959193326Sed    //         same type as, or a base class of, the class of T1, and
1960193326Sed    //         [cv2 > cv1].
1961204643Srdivacky    if (FRec == TRec || FDerivedFromT) {
1962204643Srdivacky      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
1963204643Srdivacky        // Could still fail if there's no copy constructor.
1964204643Srdivacky        // FIXME: Is this a hard error then, or just a conversion failure? The
1965204643Srdivacky        // standard doesn't say.
1966204643Srdivacky        ICS = Self.TryCopyInitialization(From, TTy,
1967204643Srdivacky                                         /*SuppressUserConversions=*/false,
1968204643Srdivacky                                         /*ForceRValue=*/false,
1969204643Srdivacky                                         /*InOverloadResolution=*/false);
1970204643Srdivacky      } else {
1971204643Srdivacky        ICS.setBad(BadConversionSequence::bad_qualifiers, From, TTy);
1972204643Srdivacky      }
1973204643Srdivacky    } else {
1974204643Srdivacky      // Can't implicitly convert FTy to a derived class TTy.
1975204643Srdivacky      // TODO: more specific error for this.
1976204643Srdivacky      ICS.setBad(BadConversionSequence::no_conversion, From, TTy);
1977193326Sed    }
1978193326Sed  } else {
1979193326Sed    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1980193326Sed    //        implicitly converted to the type that expression E2 would have
1981193326Sed    //        if E2 were converted to an rvalue.
1982193326Sed    // First find the decayed type.
1983193326Sed    if (TTy->isFunctionType())
1984193326Sed      TTy = Self.Context.getPointerType(TTy);
1985198092Srdivacky    else if (TTy->isArrayType())
1986193326Sed      TTy = Self.Context.getArrayDecayedType(TTy);
1987193326Sed
1988193326Sed    // Now try the implicit conversion.
1989193326Sed    // FIXME: This doesn't detect ambiguities.
1990198092Srdivacky    ICS = Self.TryImplicitConversion(From, TTy,
1991198092Srdivacky                                     /*SuppressUserConversions=*/false,
1992198092Srdivacky                                     /*AllowExplicit=*/false,
1993198092Srdivacky                                     /*ForceRValue=*/false,
1994198092Srdivacky                                     /*InOverloadResolution=*/false);
1995193326Sed  }
1996193326Sed  return false;
1997193326Sed}
1998193326Sed
1999193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5.
2000193326Sed///
2001193326Sed/// This is part of the parameter validation for the ? operator. If either
2002193326Sed/// value operand is a class type, overload resolution is used to find a
2003193326Sed/// conversion to a common type.
2004193326Sedstatic bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2005193326Sed                                    SourceLocation Loc) {
2006193326Sed  Expr *Args[2] = { LHS, RHS };
2007203955Srdivacky  OverloadCandidateSet CandidateSet(Loc);
2008198398Srdivacky  Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
2009193326Sed
2010193326Sed  OverloadCandidateSet::iterator Best;
2011194613Sed  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
2012200583Srdivacky    case OR_Success:
2013193326Sed      // We found a match. Perform the conversions on the arguments and move on.
2014193326Sed      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2015201361Srdivacky                                         Best->Conversions[0], Sema::AA_Converting) ||
2016193326Sed          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2017201361Srdivacky                                         Best->Conversions[1], Sema::AA_Converting))
2018193326Sed        break;
2019193326Sed      return false;
2020193326Sed
2021200583Srdivacky    case OR_No_Viable_Function:
2022193326Sed      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2023193326Sed        << LHS->getType() << RHS->getType()
2024193326Sed        << LHS->getSourceRange() << RHS->getSourceRange();
2025193326Sed      return true;
2026193326Sed
2027200583Srdivacky    case OR_Ambiguous:
2028193326Sed      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2029193326Sed        << LHS->getType() << RHS->getType()
2030193326Sed        << LHS->getSourceRange() << RHS->getSourceRange();
2031193326Sed      // FIXME: Print the possible common types by printing the return types of
2032193326Sed      // the viable candidates.
2033193326Sed      break;
2034193326Sed
2035200583Srdivacky    case OR_Deleted:
2036193326Sed      assert(false && "Conditional operator has only built-in overloads");
2037193326Sed      break;
2038193326Sed  }
2039193326Sed  return true;
2040193326Sed}
2041193326Sed
2042193326Sed/// \brief Perform an "extended" implicit conversion as returned by
2043193326Sed/// TryClassUnification.
2044193326Sed///
2045193326Sed/// TryClassUnification generates ICSs that include reference bindings.
2046193326Sed/// PerformImplicitConversion is not suitable for this; it chokes if the
2047193326Sed/// second part of a standard conversion is ICK_DerivedToBase. This function
2048193326Sed/// handles the reference binding specially.
2049193326Sedstatic bool ConvertForConditional(Sema &Self, Expr *&E,
2050198092Srdivacky                                  const ImplicitConversionSequence &ICS) {
2051202379Srdivacky  if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
2052193326Sed    assert(ICS.Standard.DirectBinding &&
2053193326Sed           "TryClassUnification should never generate indirect ref bindings");
2054193326Sed    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
2055193326Sed    // redoing all the work.
2056193326Sed    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
2057198092Srdivacky                                        TargetType(ICS)),
2058198092Srdivacky                                   /*FIXME:*/E->getLocStart(),
2059198092Srdivacky                                   /*SuppressUserConversions=*/false,
2060198092Srdivacky                                   /*AllowExplicit=*/false,
2061198092Srdivacky                                   /*ForceRValue=*/false);
2062193326Sed  }
2063202379Srdivacky  if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
2064193326Sed    assert(ICS.UserDefined.After.DirectBinding &&
2065193326Sed           "TryClassUnification should never generate indirect ref bindings");
2066193326Sed    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
2067198092Srdivacky                                        TargetType(ICS)),
2068198092Srdivacky                                   /*FIXME:*/E->getLocStart(),
2069198092Srdivacky                                   /*SuppressUserConversions=*/false,
2070198092Srdivacky                                   /*AllowExplicit=*/false,
2071198092Srdivacky                                   /*ForceRValue=*/false);
2072193326Sed  }
2073201361Srdivacky  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
2074193326Sed    return true;
2075193326Sed  return false;
2076193326Sed}
2077193326Sed
2078193326Sed/// \brief Check the operands of ?: under C++ semantics.
2079193326Sed///
2080193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2081193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.)
2082193326SedQualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2083193326Sed                                           SourceLocation QuestionLoc) {
2084193326Sed  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2085193326Sed  // interface pointers.
2086193326Sed
2087193326Sed  // C++0x 5.16p1
2088193326Sed  //   The first expression is contextually converted to bool.
2089193326Sed  if (!Cond->isTypeDependent()) {
2090193326Sed    if (CheckCXXBooleanCondition(Cond))
2091193326Sed      return QualType();
2092193326Sed  }
2093193326Sed
2094193326Sed  // Either of the arguments dependent?
2095193326Sed  if (LHS->isTypeDependent() || RHS->isTypeDependent())
2096193326Sed    return Context.DependentTy;
2097193326Sed
2098205219Srdivacky  CheckSignCompare(LHS, RHS, QuestionLoc);
2099198954Srdivacky
2100193326Sed  // C++0x 5.16p2
2101193326Sed  //   If either the second or the third operand has type (cv) void, ...
2102193326Sed  QualType LTy = LHS->getType();
2103193326Sed  QualType RTy = RHS->getType();
2104193326Sed  bool LVoid = LTy->isVoidType();
2105193326Sed  bool RVoid = RTy->isVoidType();
2106193326Sed  if (LVoid || RVoid) {
2107193326Sed    //   ... then the [l2r] conversions are performed on the second and third
2108193326Sed    //   operands ...
2109203955Srdivacky    DefaultFunctionArrayLvalueConversion(LHS);
2110203955Srdivacky    DefaultFunctionArrayLvalueConversion(RHS);
2111193326Sed    LTy = LHS->getType();
2112193326Sed    RTy = RHS->getType();
2113193326Sed
2114193326Sed    //   ... and one of the following shall hold:
2115193326Sed    //   -- The second or the third operand (but not both) is a throw-
2116193326Sed    //      expression; the result is of the type of the other and is an rvalue.
2117193326Sed    bool LThrow = isa<CXXThrowExpr>(LHS);
2118193326Sed    bool RThrow = isa<CXXThrowExpr>(RHS);
2119193326Sed    if (LThrow && !RThrow)
2120193326Sed      return RTy;
2121193326Sed    if (RThrow && !LThrow)
2122193326Sed      return LTy;
2123193326Sed
2124193326Sed    //   -- Both the second and third operands have type void; the result is of
2125193326Sed    //      type void and is an rvalue.
2126193326Sed    if (LVoid && RVoid)
2127193326Sed      return Context.VoidTy;
2128193326Sed
2129193326Sed    // Neither holds, error.
2130193326Sed    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2131193326Sed      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2132193326Sed      << LHS->getSourceRange() << RHS->getSourceRange();
2133193326Sed    return QualType();
2134193326Sed  }
2135193326Sed
2136193326Sed  // Neither is void.
2137193326Sed
2138193326Sed  // C++0x 5.16p3
2139193326Sed  //   Otherwise, if the second and third operand have different types, and
2140193326Sed  //   either has (cv) class type, and attempt is made to convert each of those
2141193326Sed  //   operands to the other.
2142193326Sed  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
2143193326Sed      (LTy->isRecordType() || RTy->isRecordType())) {
2144193326Sed    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2145193326Sed    // These return true if a single direction is already ambiguous.
2146193326Sed    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
2147193326Sed      return QualType();
2148193326Sed    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
2149193326Sed      return QualType();
2150193326Sed
2151202379Srdivacky    bool HaveL2R = !ICSLeftToRight.isBad();
2152202379Srdivacky    bool HaveR2L = !ICSRightToLeft.isBad();
2153193326Sed    //   If both can be converted, [...] the program is ill-formed.
2154193326Sed    if (HaveL2R && HaveR2L) {
2155193326Sed      Diag(QuestionLoc, diag::err_conditional_ambiguous)
2156193326Sed        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2157193326Sed      return QualType();
2158193326Sed    }
2159193326Sed
2160193326Sed    //   If exactly one conversion is possible, that conversion is applied to
2161193326Sed    //   the chosen operand and the converted operands are used in place of the
2162193326Sed    //   original operands for the remainder of this section.
2163193326Sed    if (HaveL2R) {
2164193326Sed      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
2165193326Sed        return QualType();
2166193326Sed      LTy = LHS->getType();
2167193326Sed    } else if (HaveR2L) {
2168193326Sed      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
2169193326Sed        return QualType();
2170193326Sed      RTy = RHS->getType();
2171193326Sed    }
2172193326Sed  }
2173193326Sed
2174193326Sed  // C++0x 5.16p4
2175193326Sed  //   If the second and third operands are lvalues and have the same type,
2176193326Sed  //   the result is of that type [...]
2177193326Sed  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2178193326Sed  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2179193326Sed      RHS->isLvalue(Context) == Expr::LV_Valid)
2180193326Sed    return LTy;
2181193326Sed
2182193326Sed  // C++0x 5.16p5
2183193326Sed  //   Otherwise, the result is an rvalue. If the second and third operands
2184193326Sed  //   do not have the same type, and either has (cv) class type, ...
2185193326Sed  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2186193326Sed    //   ... overload resolution is used to determine the conversions (if any)
2187193326Sed    //   to be applied to the operands. If the overload resolution fails, the
2188193326Sed    //   program is ill-formed.
2189193326Sed    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2190193326Sed      return QualType();
2191193326Sed  }
2192193326Sed
2193193326Sed  // C++0x 5.16p6
2194193326Sed  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2195193326Sed  //   conversions are performed on the second and third operands.
2196203955Srdivacky  DefaultFunctionArrayLvalueConversion(LHS);
2197203955Srdivacky  DefaultFunctionArrayLvalueConversion(RHS);
2198193326Sed  LTy = LHS->getType();
2199193326Sed  RTy = RHS->getType();
2200193326Sed
2201193326Sed  //   After those conversions, one of the following shall hold:
2202193326Sed  //   -- The second and third operands have the same type; the result
2203193326Sed  //      is of that type.
2204193326Sed  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2205193326Sed    return LTy;
2206193326Sed
2207193326Sed  //   -- The second and third operands have arithmetic or enumeration type;
2208193326Sed  //      the usual arithmetic conversions are performed to bring them to a
2209193326Sed  //      common type, and the result is of that type.
2210193326Sed  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2211193326Sed    UsualArithmeticConversions(LHS, RHS);
2212193326Sed    return LHS->getType();
2213193326Sed  }
2214193326Sed
2215193326Sed  //   -- The second and third operands have pointer type, or one has pointer
2216193326Sed  //      type and the other is a null pointer constant; pointer conversions
2217193326Sed  //      and qualification conversions are performed to bring them to their
2218193326Sed  //      composite pointer type. The result is of the composite pointer type.
2219202379Srdivacky  //   -- The second and third operands have pointer to member type, or one has
2220202379Srdivacky  //      pointer to member type and the other is a null pointer constant;
2221202379Srdivacky  //      pointer to member conversions and qualification conversions are
2222202379Srdivacky  //      performed to bring them to a common type, whose cv-qualification
2223202379Srdivacky  //      shall match the cv-qualification of either the second or the third
2224202379Srdivacky  //      operand. The result is of the common type.
2225204643Srdivacky  bool NonStandardCompositeType = false;
2226204643Srdivacky  QualType Composite = FindCompositePointerType(LHS, RHS,
2227204643Srdivacky                              isSFINAEContext()? 0 : &NonStandardCompositeType);
2228204643Srdivacky  if (!Composite.isNull()) {
2229204643Srdivacky    if (NonStandardCompositeType)
2230204643Srdivacky      Diag(QuestionLoc,
2231204643Srdivacky           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2232204643Srdivacky        << LTy << RTy << Composite
2233204643Srdivacky        << LHS->getSourceRange() << RHS->getSourceRange();
2234204643Srdivacky
2235193326Sed    return Composite;
2236204643Srdivacky  }
2237200583Srdivacky
2238200583Srdivacky  // Similarly, attempt to find composite type of twp objective-c pointers.
2239200583Srdivacky  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2240200583Srdivacky  if (!Composite.isNull())
2241200583Srdivacky    return Composite;
2242193326Sed
2243193326Sed  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2244193326Sed    << LHS->getType() << RHS->getType()
2245193326Sed    << LHS->getSourceRange() << RHS->getSourceRange();
2246193326Sed  return QualType();
2247193326Sed}
2248193326Sed
2249193326Sed/// \brief Find a merged pointer type and convert the two expressions to it.
2250193326Sed///
2251198092Srdivacky/// This finds the composite pointer type (or member pointer type) for @p E1
2252198092Srdivacky/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2253198092Srdivacky/// type and returns it.
2254193326Sed/// It does not emit diagnostics.
2255204643Srdivacky///
2256204643Srdivacky/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2257204643Srdivacky/// a non-standard (but still sane) composite type to which both expressions
2258204643Srdivacky/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2259204643Srdivacky/// will be set true.
2260204643SrdivackyQualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2261204643Srdivacky                                        bool *NonStandardCompositeType) {
2262204643Srdivacky  if (NonStandardCompositeType)
2263204643Srdivacky    *NonStandardCompositeType = false;
2264204643Srdivacky
2265193326Sed  assert(getLangOptions().CPlusPlus && "This function assumes C++");
2266193326Sed  QualType T1 = E1->getType(), T2 = E2->getType();
2267193326Sed
2268200583Srdivacky  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2269200583Srdivacky      !T2->isAnyPointerType() && !T2->isMemberPointerType())
2270198092Srdivacky   return QualType();
2271198092Srdivacky
2272193326Sed  // C++0x 5.9p2
2273193326Sed  //   Pointer conversions and qualification conversions are performed on
2274193326Sed  //   pointer operands to bring them to their composite pointer type. If
2275193326Sed  //   one operand is a null pointer constant, the composite pointer type is
2276193326Sed  //   the type of the other operand.
2277198092Srdivacky  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2278198398Srdivacky    if (T2->isMemberPointerType())
2279198398Srdivacky      ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2280198398Srdivacky    else
2281198398Srdivacky      ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
2282193326Sed    return T2;
2283193326Sed  }
2284198092Srdivacky  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2285198398Srdivacky    if (T1->isMemberPointerType())
2286198398Srdivacky      ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2287198398Srdivacky    else
2288198398Srdivacky      ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
2289193326Sed    return T1;
2290193326Sed  }
2291198092Srdivacky
2292198092Srdivacky  // Now both have to be pointers or member pointers.
2293199482Srdivacky  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2294199482Srdivacky      (!T2->isPointerType() && !T2->isMemberPointerType()))
2295193326Sed    return QualType();
2296193326Sed
2297193326Sed  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
2298193326Sed  //   the other has type "pointer to cv2 T" and the composite pointer type is
2299193326Sed  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2300193326Sed  //   Otherwise, the composite pointer type is a pointer type similar to the
2301193326Sed  //   type of one of the operands, with a cv-qualification signature that is
2302193326Sed  //   the union of the cv-qualification signatures of the operand types.
2303193326Sed  // In practice, the first part here is redundant; it's subsumed by the second.
2304193326Sed  // What we do here is, we build the two possible composite types, and try the
2305193326Sed  // conversions in both directions. If only one works, or if the two composite
2306193326Sed  // types are the same, we have succeeded.
2307198092Srdivacky  // FIXME: extended qualifiers?
2308199482Srdivacky  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2309199482Srdivacky  QualifierVector QualifierUnion;
2310199482Srdivacky  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2311199482Srdivacky      ContainingClassVector;
2312199482Srdivacky  ContainingClassVector MemberOfClass;
2313199482Srdivacky  QualType Composite1 = Context.getCanonicalType(T1),
2314199482Srdivacky           Composite2 = Context.getCanonicalType(T2);
2315204643Srdivacky  unsigned NeedConstBefore = 0;
2316198092Srdivacky  do {
2317198092Srdivacky    const PointerType *Ptr1, *Ptr2;
2318198092Srdivacky    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2319198092Srdivacky        (Ptr2 = Composite2->getAs<PointerType>())) {
2320198092Srdivacky      Composite1 = Ptr1->getPointeeType();
2321198092Srdivacky      Composite2 = Ptr2->getPointeeType();
2322204643Srdivacky
2323204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
2324204643Srdivacky      // of where we need to fill in additional 'const' qualifiers.
2325204643Srdivacky      if (NonStandardCompositeType &&
2326204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2327204643Srdivacky        NeedConstBefore = QualifierUnion.size();
2328204643Srdivacky
2329198092Srdivacky      QualifierUnion.push_back(
2330198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2331198092Srdivacky      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2332198092Srdivacky      continue;
2333198092Srdivacky    }
2334198092Srdivacky
2335198092Srdivacky    const MemberPointerType *MemPtr1, *MemPtr2;
2336198092Srdivacky    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2337198092Srdivacky        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2338198092Srdivacky      Composite1 = MemPtr1->getPointeeType();
2339198092Srdivacky      Composite2 = MemPtr2->getPointeeType();
2340204643Srdivacky
2341204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
2342204643Srdivacky      // of where we need to fill in additional 'const' qualifiers.
2343204643Srdivacky      if (NonStandardCompositeType &&
2344204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2345204643Srdivacky        NeedConstBefore = QualifierUnion.size();
2346204643Srdivacky
2347198092Srdivacky      QualifierUnion.push_back(
2348198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2349198092Srdivacky      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2350198092Srdivacky                                             MemPtr2->getClass()));
2351198092Srdivacky      continue;
2352198092Srdivacky    }
2353198092Srdivacky
2354198092Srdivacky    // FIXME: block pointer types?
2355198092Srdivacky
2356198092Srdivacky    // Cannot unwrap any more types.
2357198092Srdivacky    break;
2358198092Srdivacky  } while (true);
2359198092Srdivacky
2360204643Srdivacky  if (NeedConstBefore && NonStandardCompositeType) {
2361204643Srdivacky    // Extension: Add 'const' to qualifiers that come before the first qualifier
2362204643Srdivacky    // mismatch, so that our (non-standard!) composite type meets the
2363204643Srdivacky    // requirements of C++ [conv.qual]p4 bullet 3.
2364204643Srdivacky    for (unsigned I = 0; I != NeedConstBefore; ++I) {
2365204643Srdivacky      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2366204643Srdivacky        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2367204643Srdivacky        *NonStandardCompositeType = true;
2368204643Srdivacky      }
2369204643Srdivacky    }
2370204643Srdivacky  }
2371204643Srdivacky
2372198092Srdivacky  // Rewrap the composites as pointers or member pointers with the union CVRs.
2373199482Srdivacky  ContainingClassVector::reverse_iterator MOC
2374199482Srdivacky    = MemberOfClass.rbegin();
2375199482Srdivacky  for (QualifierVector::reverse_iterator
2376199482Srdivacky         I = QualifierUnion.rbegin(),
2377199482Srdivacky         E = QualifierUnion.rend();
2378198092Srdivacky       I != E; (void)++I, ++MOC) {
2379198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
2380198092Srdivacky    if (MOC->first && MOC->second) {
2381198092Srdivacky      // Rebuild member pointer type
2382198092Srdivacky      Composite1 = Context.getMemberPointerType(
2383198092Srdivacky                                    Context.getQualifiedType(Composite1, Quals),
2384198092Srdivacky                                    MOC->first);
2385198092Srdivacky      Composite2 = Context.getMemberPointerType(
2386198092Srdivacky                                    Context.getQualifiedType(Composite2, Quals),
2387198092Srdivacky                                    MOC->second);
2388198092Srdivacky    } else {
2389198092Srdivacky      // Rebuild pointer type
2390198092Srdivacky      Composite1
2391198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2392198092Srdivacky      Composite2
2393198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
2394198092Srdivacky    }
2395193326Sed  }
2396193326Sed
2397198092Srdivacky  ImplicitConversionSequence E1ToC1 =
2398198092Srdivacky    TryImplicitConversion(E1, Composite1,
2399198092Srdivacky                          /*SuppressUserConversions=*/false,
2400198092Srdivacky                          /*AllowExplicit=*/false,
2401198092Srdivacky                          /*ForceRValue=*/false,
2402198092Srdivacky                          /*InOverloadResolution=*/false);
2403198092Srdivacky  ImplicitConversionSequence E2ToC1 =
2404198092Srdivacky    TryImplicitConversion(E2, Composite1,
2405198092Srdivacky                          /*SuppressUserConversions=*/false,
2406198092Srdivacky                          /*AllowExplicit=*/false,
2407198092Srdivacky                          /*ForceRValue=*/false,
2408198092Srdivacky                          /*InOverloadResolution=*/false);
2409198092Srdivacky
2410204643Srdivacky  bool ToC2Viable = false;
2411193326Sed  ImplicitConversionSequence E1ToC2, E2ToC2;
2412193326Sed  if (Context.getCanonicalType(Composite1) !=
2413193326Sed      Context.getCanonicalType(Composite2)) {
2414198092Srdivacky    E1ToC2 = TryImplicitConversion(E1, Composite2,
2415198092Srdivacky                                   /*SuppressUserConversions=*/false,
2416198092Srdivacky                                   /*AllowExplicit=*/false,
2417198092Srdivacky                                   /*ForceRValue=*/false,
2418198092Srdivacky                                   /*InOverloadResolution=*/false);
2419198092Srdivacky    E2ToC2 = TryImplicitConversion(E2, Composite2,
2420198092Srdivacky                                   /*SuppressUserConversions=*/false,
2421198092Srdivacky                                   /*AllowExplicit=*/false,
2422198092Srdivacky                                   /*ForceRValue=*/false,
2423198092Srdivacky                                   /*InOverloadResolution=*/false);
2424204643Srdivacky    ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
2425193326Sed  }
2426193326Sed
2427202379Srdivacky  bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
2428193326Sed  if (ToC1Viable && !ToC2Viable) {
2429201361Srdivacky    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2430201361Srdivacky        !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
2431193326Sed      return Composite1;
2432193326Sed  }
2433193326Sed  if (ToC2Viable && !ToC1Viable) {
2434201361Srdivacky    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2435201361Srdivacky        !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
2436193326Sed      return Composite2;
2437193326Sed  }
2438193326Sed  return QualType();
2439193326Sed}
2440193326Sed
2441193326SedSema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
2442198092Srdivacky  if (!Context.getLangOptions().CPlusPlus)
2443198092Srdivacky    return Owned(E);
2444198092Srdivacky
2445201361Srdivacky  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2446201361Srdivacky
2447198092Srdivacky  const RecordType *RT = E->getType()->getAs<RecordType>();
2448193326Sed  if (!RT)
2449193326Sed    return Owned(E);
2450198092Srdivacky
2451203955Srdivacky  // If this is the result of a call expression, our source might
2452203955Srdivacky  // actually be a reference, in which case we shouldn't bind.
2453198092Srdivacky  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2454198092Srdivacky    QualType Ty = CE->getCallee()->getType();
2455198092Srdivacky    if (const PointerType *PT = Ty->getAs<PointerType>())
2456198092Srdivacky      Ty = PT->getPointeeType();
2457204643Srdivacky    else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2458204643Srdivacky      Ty = BPT->getPointeeType();
2459204643Srdivacky
2460198092Srdivacky    const FunctionType *FTy = Ty->getAs<FunctionType>();
2461198092Srdivacky    if (FTy->getResultType()->isReferenceType())
2462198092Srdivacky      return Owned(E);
2463198092Srdivacky  }
2464203955Srdivacky
2465203955Srdivacky  // That should be enough to guarantee that this type is complete.
2466203955Srdivacky  // If it has a trivial destructor, we can avoid the extra copy.
2467203955Srdivacky  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2468203955Srdivacky  if (RD->hasTrivialDestructor())
2469203955Srdivacky    return Owned(E);
2470203955Srdivacky
2471198092Srdivacky  CXXTemporary *Temp = CXXTemporary::Create(Context,
2472193326Sed                                            RD->getDestructor(Context));
2473193326Sed  ExprTemporaries.push_back(Temp);
2474198092Srdivacky  if (CXXDestructorDecl *Destructor =
2475198092Srdivacky        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2476198092Srdivacky    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2477193326Sed  // FIXME: Add the temporary to the temporaries vector.
2478193326Sed  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2479193326Sed}
2480193326Sed
2481201361SrdivackyExpr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
2482193576Sed  assert(SubExpr && "sub expression can't be null!");
2483198092Srdivacky
2484200583Srdivacky  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2485200583Srdivacky  assert(ExprTemporaries.size() >= FirstTemporary);
2486200583Srdivacky  if (ExprTemporaries.size() == FirstTemporary)
2487193576Sed    return SubExpr;
2488198092Srdivacky
2489193576Sed  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2490200583Srdivacky                                           &ExprTemporaries[FirstTemporary],
2491201361Srdivacky                                       ExprTemporaries.size() - FirstTemporary);
2492200583Srdivacky  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2493200583Srdivacky                        ExprTemporaries.end());
2494198092Srdivacky
2495193576Sed  return E;
2496193576Sed}
2497193576Sed
2498201361SrdivackySema::OwningExprResult
2499201361SrdivackySema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2500201361Srdivacky  if (SubExpr.isInvalid())
2501201361Srdivacky    return ExprError();
2502201361Srdivacky
2503201361Srdivacky  return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2504201361Srdivacky}
2505201361Srdivacky
2506201361SrdivackyFullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2507201361Srdivacky  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2508201361Srdivacky  assert(ExprTemporaries.size() >= FirstTemporary);
2509201361Srdivacky
2510201361Srdivacky  unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2511201361Srdivacky  CXXTemporary **Temporaries =
2512201361Srdivacky    NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2513201361Srdivacky
2514201361Srdivacky  FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2515201361Srdivacky
2516201361Srdivacky  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2517201361Srdivacky                        ExprTemporaries.end());
2518201361Srdivacky
2519201361Srdivacky  return E;
2520201361Srdivacky}
2521201361Srdivacky
2522198092SrdivackySema::OwningExprResult
2523198092SrdivackySema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2524204643Srdivacky                                   tok::TokenKind OpKind, TypeTy *&ObjectType,
2525204643Srdivacky                                   bool &MayBePseudoDestructor) {
2526198092Srdivacky  // Since this might be a postfix expression, get rid of ParenListExprs.
2527198092Srdivacky  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2528198092Srdivacky
2529198092Srdivacky  Expr *BaseExpr = (Expr*)Base.get();
2530198092Srdivacky  assert(BaseExpr && "no record expansion");
2531198092Srdivacky
2532198092Srdivacky  QualType BaseType = BaseExpr->getType();
2533204643Srdivacky  MayBePseudoDestructor = false;
2534198092Srdivacky  if (BaseType->isDependentType()) {
2535198954Srdivacky    // If we have a pointer to a dependent type and are using the -> operator,
2536198954Srdivacky    // the object type is the type that the pointer points to. We might still
2537198954Srdivacky    // have enough information about that type to do something useful.
2538198954Srdivacky    if (OpKind == tok::arrow)
2539198954Srdivacky      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2540198954Srdivacky        BaseType = Ptr->getPointeeType();
2541198954Srdivacky
2542198092Srdivacky    ObjectType = BaseType.getAsOpaquePtr();
2543204643Srdivacky    MayBePseudoDestructor = true;
2544198092Srdivacky    return move(Base);
2545198092Srdivacky  }
2546198092Srdivacky
2547198092Srdivacky  // C++ [over.match.oper]p8:
2548198092Srdivacky  //   [...] When operator->returns, the operator-> is applied  to the value
2549198092Srdivacky  //   returned, with the original second operand.
2550198092Srdivacky  if (OpKind == tok::arrow) {
2551198092Srdivacky    // The set of types we've considered so far.
2552198092Srdivacky    llvm::SmallPtrSet<CanQualType,8> CTypes;
2553198092Srdivacky    llvm::SmallVector<SourceLocation, 8> Locations;
2554198092Srdivacky    CTypes.insert(Context.getCanonicalType(BaseType));
2555198092Srdivacky
2556198092Srdivacky    while (BaseType->isRecordType()) {
2557198092Srdivacky      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2558198092Srdivacky      BaseExpr = (Expr*)Base.get();
2559198092Srdivacky      if (BaseExpr == NULL)
2560198092Srdivacky        return ExprError();
2561198092Srdivacky      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2562198092Srdivacky        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2563198092Srdivacky      BaseType = BaseExpr->getType();
2564198092Srdivacky      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2565198092Srdivacky      if (!CTypes.insert(CBaseType)) {
2566198092Srdivacky        Diag(OpLoc, diag::err_operator_arrow_circular);
2567198092Srdivacky        for (unsigned i = 0; i < Locations.size(); i++)
2568198092Srdivacky          Diag(Locations[i], diag::note_declared_at);
2569198092Srdivacky        return ExprError();
2570198092Srdivacky      }
2571198092Srdivacky    }
2572199990Srdivacky
2573199990Srdivacky    if (BaseType->isPointerType())
2574199990Srdivacky      BaseType = BaseType->getPointeeType();
2575198092Srdivacky  }
2576198092Srdivacky
2577198092Srdivacky  // We could end up with various non-record types here, such as extended
2578198092Srdivacky  // vector types or Objective-C interfaces. Just return early and let
2579198092Srdivacky  // ActOnMemberReferenceExpr do the work.
2580198092Srdivacky  if (!BaseType->isRecordType()) {
2581198092Srdivacky    // C++ [basic.lookup.classref]p2:
2582198092Srdivacky    //   [...] If the type of the object expression is of pointer to scalar
2583198092Srdivacky    //   type, the unqualified-id is looked up in the context of the complete
2584198092Srdivacky    //   postfix-expression.
2585204643Srdivacky    //
2586204643Srdivacky    // This also indicates that we should be parsing a
2587204643Srdivacky    // pseudo-destructor-name.
2588198092Srdivacky    ObjectType = 0;
2589204643Srdivacky    MayBePseudoDestructor = true;
2590198092Srdivacky    return move(Base);
2591198092Srdivacky  }
2592198092Srdivacky
2593199482Srdivacky  // The object type must be complete (or dependent).
2594199482Srdivacky  if (!BaseType->isDependentType() &&
2595199482Srdivacky      RequireCompleteType(OpLoc, BaseType,
2596199482Srdivacky                          PDiag(diag::err_incomplete_member_access)))
2597199482Srdivacky    return ExprError();
2598199482Srdivacky
2599198092Srdivacky  // C++ [basic.lookup.classref]p2:
2600198092Srdivacky  //   If the id-expression in a class member access (5.2.5) is an
2601199482Srdivacky  //   unqualified-id, and the type of the object expression is of a class
2602198092Srdivacky  //   type C (or of pointer to a class type C), the unqualified-id is looked
2603198092Srdivacky  //   up in the scope of class C. [...]
2604198092Srdivacky  ObjectType = BaseType.getAsOpaquePtr();
2605198092Srdivacky  return move(Base);
2606198092Srdivacky}
2607198092Srdivacky
2608204643SrdivackySema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2609204643Srdivacky                                                   ExprArg MemExpr) {
2610204643Srdivacky  Expr *E = (Expr *) MemExpr.get();
2611204643Srdivacky  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2612204643Srdivacky  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2613204643Srdivacky    << isa<CXXPseudoDestructorExpr>(E)
2614204643Srdivacky    << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2615204643Srdivacky
2616204643Srdivacky  return ActOnCallExpr(/*Scope*/ 0,
2617204643Srdivacky                       move(MemExpr),
2618204643Srdivacky                       /*LPLoc*/ ExpectedLParenLoc,
2619204643Srdivacky                       Sema::MultiExprArg(*this, 0, 0),
2620204643Srdivacky                       /*CommaLocs*/ 0,
2621204643Srdivacky                       /*RPLoc*/ ExpectedLParenLoc);
2622204643Srdivacky}
2623204643Srdivacky
2624204643SrdivackySema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2625204643Srdivacky                                                       SourceLocation OpLoc,
2626204643Srdivacky                                                       tok::TokenKind OpKind,
2627204643Srdivacky                                                       const CXXScopeSpec &SS,
2628204643Srdivacky                                                 TypeSourceInfo *ScopeTypeInfo,
2629204643Srdivacky                                                       SourceLocation CCLoc,
2630204643Srdivacky                                                       SourceLocation TildeLoc,
2631204643Srdivacky                                         PseudoDestructorTypeStorage Destructed,
2632204643Srdivacky                                                       bool HasTrailingLParen) {
2633204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
2634204643Srdivacky
2635204643Srdivacky  // C++ [expr.pseudo]p2:
2636204643Srdivacky  //   The left-hand side of the dot operator shall be of scalar type. The
2637204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2638204643Srdivacky  //   This scalar type is the object type.
2639204643Srdivacky  Expr *BaseE = (Expr *)Base.get();
2640204643Srdivacky  QualType ObjectType = BaseE->getType();
2641204643Srdivacky  if (OpKind == tok::arrow) {
2642204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2643204643Srdivacky      ObjectType = Ptr->getPointeeType();
2644204643Srdivacky    } else if (!BaseE->isTypeDependent()) {
2645204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
2646204643Srdivacky      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2647204643Srdivacky        << ObjectType << true
2648204643Srdivacky        << CodeModificationHint::CreateReplacement(OpLoc, ".");
2649204643Srdivacky      if (isSFINAEContext())
2650204643Srdivacky        return ExprError();
2651204643Srdivacky
2652204643Srdivacky      OpKind = tok::period;
2653204643Srdivacky    }
2654204643Srdivacky  }
2655204643Srdivacky
2656204643Srdivacky  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2657204643Srdivacky    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2658204643Srdivacky      << ObjectType << BaseE->getSourceRange();
2659204643Srdivacky    return ExprError();
2660204643Srdivacky  }
2661204643Srdivacky
2662204643Srdivacky  // C++ [expr.pseudo]p2:
2663204643Srdivacky  //   [...] The cv-unqualified versions of the object type and of the type
2664204643Srdivacky  //   designated by the pseudo-destructor-name shall be the same type.
2665204643Srdivacky  if (DestructedTypeInfo) {
2666204643Srdivacky    QualType DestructedType = DestructedTypeInfo->getType();
2667204643Srdivacky    SourceLocation DestructedTypeStart
2668204643Srdivacky      = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2669204643Srdivacky    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2670204643Srdivacky        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2671204643Srdivacky      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2672204643Srdivacky        << ObjectType << DestructedType << BaseE->getSourceRange()
2673204643Srdivacky        << DestructedTypeInfo->getTypeLoc().getSourceRange();
2674204643Srdivacky
2675204643Srdivacky      // Recover by setting the destructed type to the object type.
2676204643Srdivacky      DestructedType = ObjectType;
2677204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2678204643Srdivacky                                                           DestructedTypeStart);
2679204643Srdivacky      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2680204643Srdivacky    }
2681204643Srdivacky  }
2682204643Srdivacky
2683204643Srdivacky  // C++ [expr.pseudo]p2:
2684204643Srdivacky  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2685204643Srdivacky  //   form
2686204643Srdivacky  //
2687204643Srdivacky  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2688204643Srdivacky  //
2689204643Srdivacky  //   shall designate the same scalar type.
2690204643Srdivacky  if (ScopeTypeInfo) {
2691204643Srdivacky    QualType ScopeType = ScopeTypeInfo->getType();
2692204643Srdivacky    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2693204643Srdivacky        !Context.hasSameType(ScopeType, ObjectType)) {
2694204643Srdivacky
2695204643Srdivacky      Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2696204643Srdivacky           diag::err_pseudo_dtor_type_mismatch)
2697204643Srdivacky        << ObjectType << ScopeType << BaseE->getSourceRange()
2698204643Srdivacky        << ScopeTypeInfo->getTypeLoc().getSourceRange();
2699204643Srdivacky
2700204643Srdivacky      ScopeType = QualType();
2701204643Srdivacky      ScopeTypeInfo = 0;
2702204643Srdivacky    }
2703204643Srdivacky  }
2704204643Srdivacky
2705204643Srdivacky  OwningExprResult Result
2706204643Srdivacky    = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2707204643Srdivacky                                                  Base.takeAs<Expr>(),
2708204643Srdivacky                                                  OpKind == tok::arrow,
2709204643Srdivacky                                                  OpLoc,
2710204643Srdivacky                                       (NestedNameSpecifier *) SS.getScopeRep(),
2711204643Srdivacky                                                  SS.getRange(),
2712204643Srdivacky                                                  ScopeTypeInfo,
2713204643Srdivacky                                                  CCLoc,
2714204643Srdivacky                                                  TildeLoc,
2715204643Srdivacky                                                  Destructed));
2716204643Srdivacky
2717204643Srdivacky  if (HasTrailingLParen)
2718204643Srdivacky    return move(Result);
2719204643Srdivacky
2720204643Srdivacky  return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
2721204643Srdivacky}
2722204643Srdivacky
2723204643SrdivackySema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2724204643Srdivacky                                                       SourceLocation OpLoc,
2725204643Srdivacky                                                       tok::TokenKind OpKind,
2726204643Srdivacky                                                       const CXXScopeSpec &SS,
2727204643Srdivacky                                                  UnqualifiedId &FirstTypeName,
2728204643Srdivacky                                                       SourceLocation CCLoc,
2729204643Srdivacky                                                       SourceLocation TildeLoc,
2730204643Srdivacky                                                 UnqualifiedId &SecondTypeName,
2731204643Srdivacky                                                       bool HasTrailingLParen) {
2732204643Srdivacky  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2733204643Srdivacky          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2734204643Srdivacky         "Invalid first type name in pseudo-destructor");
2735204643Srdivacky  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2736204643Srdivacky          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2737204643Srdivacky         "Invalid second type name in pseudo-destructor");
2738204643Srdivacky
2739204643Srdivacky  Expr *BaseE = (Expr *)Base.get();
2740204643Srdivacky
2741204643Srdivacky  // C++ [expr.pseudo]p2:
2742204643Srdivacky  //   The left-hand side of the dot operator shall be of scalar type. The
2743204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2744204643Srdivacky  //   This scalar type is the object type.
2745204643Srdivacky  QualType ObjectType = BaseE->getType();
2746204643Srdivacky  if (OpKind == tok::arrow) {
2747204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2748204643Srdivacky      ObjectType = Ptr->getPointeeType();
2749204643Srdivacky    } else if (!ObjectType->isDependentType()) {
2750204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
2751204643Srdivacky      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2752204643Srdivacky        << ObjectType << true
2753204643Srdivacky        << CodeModificationHint::CreateReplacement(OpLoc, ".");
2754204643Srdivacky      if (isSFINAEContext())
2755204643Srdivacky        return ExprError();
2756204643Srdivacky
2757204643Srdivacky      OpKind = tok::period;
2758204643Srdivacky    }
2759204643Srdivacky  }
2760204643Srdivacky
2761204643Srdivacky  // Compute the object type that we should use for name lookup purposes. Only
2762204643Srdivacky  // record types and dependent types matter.
2763204643Srdivacky  void *ObjectTypePtrForLookup = 0;
2764204643Srdivacky  if (!SS.isSet()) {
2765204643Srdivacky    ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2766204643Srdivacky    if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2767204643Srdivacky      ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2768204643Srdivacky  }
2769204643Srdivacky
2770204643Srdivacky  // Convert the name of the type being destructed (following the ~) into a
2771204643Srdivacky  // type (with source-location information).
2772204643Srdivacky  QualType DestructedType;
2773204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = 0;
2774204643Srdivacky  PseudoDestructorTypeStorage Destructed;
2775204643Srdivacky  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2776204643Srdivacky    TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2777204643Srdivacky                            SecondTypeName.StartLocation,
2778204643Srdivacky                            S, &SS, true, ObjectTypePtrForLookup);
2779204643Srdivacky    if (!T &&
2780204643Srdivacky        ((SS.isSet() && !computeDeclContext(SS, false)) ||
2781204643Srdivacky         (!SS.isSet() && ObjectType->isDependentType()))) {
2782204643Srdivacky      // The name of the type being destroyed is a dependent name, and we
2783204643Srdivacky      // couldn't find anything useful in scope. Just store the identifier and
2784204643Srdivacky      // it's location, and we'll perform (qualified) name lookup again at
2785204643Srdivacky      // template instantiation time.
2786204643Srdivacky      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2787204643Srdivacky                                               SecondTypeName.StartLocation);
2788204643Srdivacky    } else if (!T) {
2789204643Srdivacky      Diag(SecondTypeName.StartLocation,
2790204643Srdivacky           diag::err_pseudo_dtor_destructor_non_type)
2791204643Srdivacky        << SecondTypeName.Identifier << ObjectType;
2792204643Srdivacky      if (isSFINAEContext())
2793204643Srdivacky        return ExprError();
2794204643Srdivacky
2795204643Srdivacky      // Recover by assuming we had the right type all along.
2796204643Srdivacky      DestructedType = ObjectType;
2797204643Srdivacky    } else
2798204643Srdivacky      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2799204643Srdivacky  } else {
2800204643Srdivacky    // Resolve the template-id to a type.
2801204643Srdivacky    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2802204643Srdivacky    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2803204643Srdivacky                                       TemplateId->getTemplateArgs(),
2804204643Srdivacky                                       TemplateId->NumArgs);
2805204643Srdivacky    TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2806204643Srdivacky                                       TemplateId->TemplateNameLoc,
2807204643Srdivacky                                       TemplateId->LAngleLoc,
2808204643Srdivacky                                       TemplateArgsPtr,
2809204643Srdivacky                                       TemplateId->RAngleLoc);
2810204643Srdivacky    if (T.isInvalid() || !T.get()) {
2811204643Srdivacky      // Recover by assuming we had the right type all along.
2812204643Srdivacky      DestructedType = ObjectType;
2813204643Srdivacky    } else
2814204643Srdivacky      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
2815204643Srdivacky  }
2816204643Srdivacky
2817204643Srdivacky  // If we've performed some kind of recovery, (re-)build the type source
2818204643Srdivacky  // information.
2819204643Srdivacky  if (!DestructedType.isNull()) {
2820204643Srdivacky    if (!DestructedTypeInfo)
2821204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
2822204643Srdivacky                                                  SecondTypeName.StartLocation);
2823204643Srdivacky    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2824204643Srdivacky  }
2825204643Srdivacky
2826204643Srdivacky  // Convert the name of the scope type (the type prior to '::') into a type.
2827204643Srdivacky  TypeSourceInfo *ScopeTypeInfo = 0;
2828204643Srdivacky  QualType ScopeType;
2829204643Srdivacky  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2830204643Srdivacky      FirstTypeName.Identifier) {
2831204643Srdivacky    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2832204643Srdivacky      TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2833204643Srdivacky                              FirstTypeName.StartLocation,
2834204643Srdivacky                              S, &SS, false, ObjectTypePtrForLookup);
2835204643Srdivacky      if (!T) {
2836204643Srdivacky        Diag(FirstTypeName.StartLocation,
2837204643Srdivacky             diag::err_pseudo_dtor_destructor_non_type)
2838204643Srdivacky          << FirstTypeName.Identifier << ObjectType;
2839204643Srdivacky
2840204643Srdivacky        if (isSFINAEContext())
2841204643Srdivacky          return ExprError();
2842204643Srdivacky
2843204643Srdivacky        // Just drop this type. It's unnecessary anyway.
2844204643Srdivacky        ScopeType = QualType();
2845204643Srdivacky      } else
2846204643Srdivacky        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
2847204643Srdivacky    } else {
2848204643Srdivacky      // Resolve the template-id to a type.
2849204643Srdivacky      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
2850204643Srdivacky      ASTTemplateArgsPtr TemplateArgsPtr(*this,
2851204643Srdivacky                                         TemplateId->getTemplateArgs(),
2852204643Srdivacky                                         TemplateId->NumArgs);
2853204643Srdivacky      TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2854204643Srdivacky                                         TemplateId->TemplateNameLoc,
2855204643Srdivacky                                         TemplateId->LAngleLoc,
2856204643Srdivacky                                         TemplateArgsPtr,
2857204643Srdivacky                                         TemplateId->RAngleLoc);
2858204643Srdivacky      if (T.isInvalid() || !T.get()) {
2859204643Srdivacky        // Recover by dropping this type.
2860204643Srdivacky        ScopeType = QualType();
2861204643Srdivacky      } else
2862204643Srdivacky        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
2863204643Srdivacky    }
2864204643Srdivacky  }
2865204643Srdivacky
2866204643Srdivacky  if (!ScopeType.isNull() && !ScopeTypeInfo)
2867204643Srdivacky    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2868204643Srdivacky                                                  FirstTypeName.StartLocation);
2869204643Srdivacky
2870204643Srdivacky
2871204643Srdivacky  return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
2872204643Srdivacky                                   ScopeTypeInfo, CCLoc, TildeLoc,
2873204643Srdivacky                                   Destructed, HasTrailingLParen);
2874204643Srdivacky}
2875204643Srdivacky
2876198092SrdivackyCXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2877198092Srdivacky                                                CXXMethodDecl *Method) {
2878204793Srdivacky  if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, Method))
2879200583Srdivacky    assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2880200583Srdivacky
2881198092Srdivacky  MemberExpr *ME =
2882198092Srdivacky      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2883198092Srdivacky                               SourceLocation(), Method->getType());
2884200583Srdivacky  QualType ResultType = Method->getResultType().getNonReferenceType();
2885199990Srdivacky  MarkDeclarationReferenced(Exp->getLocStart(), Method);
2886199990Srdivacky  CXXMemberCallExpr *CE =
2887199990Srdivacky    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2888199990Srdivacky                                    Exp->getLocEnd());
2889198092Srdivacky  return CE;
2890198092Srdivacky}
2891198092Srdivacky
2892198092SrdivackySema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2893198092Srdivacky                                                  QualType Ty,
2894198092Srdivacky                                                  CastExpr::CastKind Kind,
2895198092Srdivacky                                                  CXXMethodDecl *Method,
2896198092Srdivacky                                                  ExprArg Arg) {
2897198092Srdivacky  Expr *From = Arg.takeAs<Expr>();
2898198092Srdivacky
2899198092Srdivacky  switch (Kind) {
2900198092Srdivacky  default: assert(0 && "Unhandled cast kind!");
2901198092Srdivacky  case CastExpr::CK_ConstructorConversion: {
2902198092Srdivacky    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2903198092Srdivacky
2904198092Srdivacky    if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2905198092Srdivacky                                MultiExprArg(*this, (void **)&From, 1),
2906198092Srdivacky                                CastLoc, ConstructorArgs))
2907198092Srdivacky      return ExprError();
2908198398Srdivacky
2909198398Srdivacky    OwningExprResult Result =
2910198398Srdivacky      BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2911198398Srdivacky                            move_arg(ConstructorArgs));
2912198398Srdivacky    if (Result.isInvalid())
2913198398Srdivacky      return ExprError();
2914198398Srdivacky
2915198398Srdivacky    return MaybeBindToTemporary(Result.takeAs<Expr>());
2916198092Srdivacky  }
2917198092Srdivacky
2918198092Srdivacky  case CastExpr::CK_UserDefinedConversion: {
2919198092Srdivacky    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2920200583Srdivacky
2921198092Srdivacky    // Create an implicit call expr that calls it.
2922198092Srdivacky    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
2923198398Srdivacky    return MaybeBindToTemporary(CE);
2924198092Srdivacky  }
2925198092Srdivacky  }
2926198092Srdivacky}
2927198092Srdivacky
2928193326SedSema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2929193326Sed  Expr *FullExpr = Arg.takeAs<Expr>();
2930193576Sed  if (FullExpr)
2931201361Srdivacky    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
2932193326Sed
2933193326Sed  return Owned(FullExpr);
2934193326Sed}
2935