1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SemaInherit.h"
15 #include "Sema.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Parse/DeclSpec.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 using namespace clang;
23 
24 /// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
25 /// name (e.g., operator void const *) as an expression. This is
26 /// very similar to ActOnIdentifierExpr, except that instead of
27 /// providing an identifier the parser provides the type of the
28 /// conversion function.
29 Sema::OwningExprResult
30 Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31                                      TypeTy *Ty, bool HasTrailingLParen,
32                                      const CXXScopeSpec &SS,
33                                      bool isAddressOfOperand) {
34   QualType ConvType = QualType::getFromOpaquePtr(Ty);
35   QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36   DeclarationName ConvName
37     = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
38   return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
39                                   &SS, isAddressOfOperand);
40 }
41 
42 /// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
43 /// name (e.g., @c operator+ ) as an expression. This is very
44 /// similar to ActOnIdentifierExpr, except that instead of providing
45 /// an identifier the parser provides the kind of overloaded
46 /// operator that was parsed.
47 Sema::OwningExprResult
48 Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49                                      OverloadedOperatorKind Op,
50                                      bool HasTrailingLParen,
51                                      const CXXScopeSpec &SS,
52                                      bool isAddressOfOperand) {
53   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
54   return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
55                                   isAddressOfOperand);
56 }
57 
58 /// ActOnCXXTypeidOfType - Parse typeid( type-id ).
59 Action::OwningExprResult
60 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
62   NamespaceDecl *StdNs = GetStdNamespace();
63   if (!StdNs)
64     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
65 
66   IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
67   Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
68   RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
69   if (!TypeInfoRecordDecl)
70     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
71 
72   QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73 
74   if (!isType) {
75     // C++0x [expr.typeid]p3:
76     //   When typeid is applied to an expression other than an lvalue of a
77     //   polymorphic class type [...] [the] expression is an unevaluated
78     //   operand.
79 
80     // FIXME: if the type of the expression is a class type, the class
81     // shall be completely defined.
82     bool isUnevaluatedOperand = true;
83     Expr *E = static_cast<Expr *>(TyOrExpr);
84     if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
85       QualType T = E->getType();
86       if (const RecordType *RecordT = T->getAs<RecordType>()) {
87         CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
88         if (RecordD->isPolymorphic())
89           isUnevaluatedOperand = false;
90       }
91     }
92 
93     // If this is an unevaluated operand, clear out the set of declaration
94     // references we have been computing.
95     if (isUnevaluatedOperand)
96       PotentiallyReferencedDeclStack.back().clear();
97   }
98 
99   return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
100                                            TypeInfoType.withConst(),
101                                            SourceRange(OpLoc, RParenLoc)));
102 }
103 
104 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
105 Action::OwningExprResult
106 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
107   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
108          "Unknown C++ Boolean value!");
109   return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
110                                                 Context.BoolTy, OpLoc));
111 }
112 
113 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
114 Action::OwningExprResult
115 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
116   return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
117 }
118 
119 /// ActOnCXXThrow - Parse throw expressions.
120 Action::OwningExprResult
121 Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
122   Expr *Ex = E.takeAs<Expr>();
123   if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
124     return ExprError();
125   return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
126 }
127 
128 /// CheckCXXThrowOperand - Validate the operand of a throw.
129 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
130   // C++ [except.throw]p3:
131   //   [...] adjusting the type from "array of T" or "function returning T"
132   //   to "pointer to T" or "pointer to function returning T", [...]
133   DefaultFunctionArrayConversion(E);
134 
135   //   If the type of the exception would be an incomplete type or a pointer
136   //   to an incomplete type other than (cv) void the program is ill-formed.
137   QualType Ty = E->getType();
138   int isPointer = 0;
139   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
140     Ty = Ptr->getPointeeType();
141     isPointer = 1;
142   }
143   if (!isPointer || !Ty->isVoidType()) {
144     if (RequireCompleteType(ThrowLoc, Ty,
145                             isPointer ? diag::err_throw_incomplete_ptr
146                                       : diag::err_throw_incomplete,
147                             E->getSourceRange(), SourceRange(), QualType()))
148       return true;
149   }
150 
151   // FIXME: Construct a temporary here.
152   return false;
153 }
154 
155 Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
156   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
157   /// is a non-lvalue expression whose value is the address of the object for
158   /// which the function is called.
159 
160   if (!isa<FunctionDecl>(CurContext))
161     return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
162 
163   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
164     if (MD->isInstance())
165       return Owned(new (Context) CXXThisExpr(ThisLoc,
166                                              MD->getThisType(Context)));
167 
168   return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
169 }
170 
171 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
172 /// Can be interpreted either as function-style casting ("int(x)")
173 /// or class type construction ("ClassType(x,y,z)")
174 /// or creation of a value-initialized type ("int()").
175 Action::OwningExprResult
176 Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
177                                 SourceLocation LParenLoc,
178                                 MultiExprArg exprs,
179                                 SourceLocation *CommaLocs,
180                                 SourceLocation RParenLoc) {
181   assert(TypeRep && "Missing type!");
182   QualType Ty = QualType::getFromOpaquePtr(TypeRep);
183   unsigned NumExprs = exprs.size();
184   Expr **Exprs = (Expr**)exprs.get();
185   SourceLocation TyBeginLoc = TypeRange.getBegin();
186   SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
187 
188   if (Ty->isDependentType() ||
189       CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
190     exprs.release();
191 
192     return Owned(CXXUnresolvedConstructExpr::Create(Context,
193                                                     TypeRange.getBegin(), Ty,
194                                                     LParenLoc,
195                                                     Exprs, NumExprs,
196                                                     RParenLoc));
197   }
198 
199 
200   // C++ [expr.type.conv]p1:
201   // If the expression list is a single expression, the type conversion
202   // expression is equivalent (in definedness, and if defined in meaning) to the
203   // corresponding cast expression.
204   //
205   if (NumExprs == 1) {
206     if (CheckCastTypes(TypeRange, Ty, Exprs[0], /*functional-style*/true))
207       return ExprError();
208     exprs.release();
209     return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
210                                                      Ty, TyBeginLoc,
211                                                      CastExpr::CK_Unknown,
212                                                      Exprs[0], RParenLoc));
213   }
214 
215   if (const RecordType *RT = Ty->getAs<RecordType>()) {
216     CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
217 
218     // FIXME: We should always create a CXXTemporaryObjectExpr here unless
219     // both the ctor and dtor are trivial.
220     if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
221       CXXConstructorDecl *Constructor
222         = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
223                                              TypeRange.getBegin(),
224                                              SourceRange(TypeRange.getBegin(),
225                                                          RParenLoc),
226                                              DeclarationName(),
227                                              IK_Direct);
228 
229       if (!Constructor)
230         return ExprError();
231 
232       exprs.release();
233       Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
234                                                      Ty, TyBeginLoc, Exprs,
235                                                      NumExprs, RParenLoc);
236       return MaybeBindToTemporary(E);
237     }
238 
239     // Fall through to value-initialize an object of class type that
240     // doesn't have a user-declared default constructor.
241   }
242 
243   // C++ [expr.type.conv]p1:
244   // If the expression list specifies more than a single value, the type shall
245   // be a class with a suitably declared constructor.
246   //
247   if (NumExprs > 1)
248     return ExprError(Diag(CommaLocs[0],
249                           diag::err_builtin_func_cast_more_than_one_arg)
250       << FullRange);
251 
252   assert(NumExprs == 0 && "Expected 0 expressions");
253 
254   // C++ [expr.type.conv]p2:
255   // The expression T(), where T is a simple-type-specifier for a non-array
256   // complete object type or the (possibly cv-qualified) void type, creates an
257   // rvalue of the specified type, which is value-initialized.
258   //
259   if (Ty->isArrayType())
260     return ExprError(Diag(TyBeginLoc,
261                           diag::err_value_init_for_array_type) << FullRange);
262   if (!Ty->isDependentType() && !Ty->isVoidType() &&
263       RequireCompleteType(TyBeginLoc, Ty,
264                           diag::err_invalid_incomplete_type_use, FullRange))
265     return ExprError();
266 
267   if (RequireNonAbstractType(TyBeginLoc, Ty,
268                              diag::err_allocation_of_abstract_type))
269     return ExprError();
270 
271   exprs.release();
272   return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
273 }
274 
275 
276 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
277 /// @code new (memory) int[size][4] @endcode
278 /// or
279 /// @code ::new Foo(23, "hello") @endcode
280 /// For the interpretation of this heap of arguments, consult the base version.
281 Action::OwningExprResult
282 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
283                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
284                   SourceLocation PlacementRParen, bool ParenTypeId,
285                   Declarator &D, SourceLocation ConstructorLParen,
286                   MultiExprArg ConstructorArgs,
287                   SourceLocation ConstructorRParen)
288 {
289   Expr *ArraySize = 0;
290   unsigned Skip = 0;
291   // If the specified type is an array, unwrap it and save the expression.
292   if (D.getNumTypeObjects() > 0 &&
293       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
294     DeclaratorChunk &Chunk = D.getTypeObject(0);
295     if (Chunk.Arr.hasStatic)
296       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
297         << D.getSourceRange());
298     if (!Chunk.Arr.NumElts)
299       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
300         << D.getSourceRange());
301     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
302     Skip = 1;
303   }
304 
305   QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
306   if (D.isInvalidType())
307     return ExprError();
308 
309   // Every dimension shall be of constant size.
310   unsigned i = 1;
311   QualType ElementType = AllocType;
312   while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
313     if (!Array->isConstantArrayType()) {
314       Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
315         << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
316       return ExprError();
317     }
318     ElementType = Array->getElementType();
319     ++i;
320   }
321 
322   return BuildCXXNew(StartLoc, UseGlobal,
323                      PlacementLParen,
324                      move(PlacementArgs),
325                      PlacementRParen,
326                      ParenTypeId,
327                      AllocType,
328                      D.getSourceRange().getBegin(),
329                      D.getSourceRange(),
330                      Owned(ArraySize),
331                      ConstructorLParen,
332                      move(ConstructorArgs),
333                      ConstructorRParen);
334 }
335 
336 Sema::OwningExprResult
337 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
338                   SourceLocation PlacementLParen,
339                   MultiExprArg PlacementArgs,
340                   SourceLocation PlacementRParen,
341                   bool ParenTypeId,
342                   QualType AllocType,
343                   SourceLocation TypeLoc,
344                   SourceRange TypeRange,
345                   ExprArg ArraySizeE,
346                   SourceLocation ConstructorLParen,
347                   MultiExprArg ConstructorArgs,
348                   SourceLocation ConstructorRParen) {
349   if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
350     return ExprError();
351 
352   QualType ResultType = Context.getPointerType(AllocType);
353 
354   // That every array dimension except the first is constant was already
355   // checked by the type check above.
356 
357   // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
358   //   or enumeration type with a non-negative value."
359   Expr *ArraySize = (Expr *)ArraySizeE.get();
360   if (ArraySize && !ArraySize->isTypeDependent()) {
361     QualType SizeType = ArraySize->getType();
362     if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
363       return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
364                             diag::err_array_size_not_integral)
365         << SizeType << ArraySize->getSourceRange());
366     // Let's see if this is a constant < 0. If so, we reject it out of hand.
367     // We don't care about special rules, so we tell the machinery it's not
368     // evaluated - it gives us a result in more cases.
369     if (!ArraySize->isValueDependent()) {
370       llvm::APSInt Value;
371       if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
372         if (Value < llvm::APSInt(
373                         llvm::APInt::getNullValue(Value.getBitWidth()), false))
374           return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
375                            diag::err_typecheck_negative_array_size)
376             << ArraySize->getSourceRange());
377       }
378     }
379   }
380 
381   FunctionDecl *OperatorNew = 0;
382   FunctionDecl *OperatorDelete = 0;
383   Expr **PlaceArgs = (Expr**)PlacementArgs.get();
384   unsigned NumPlaceArgs = PlacementArgs.size();
385   if (!AllocType->isDependentType() &&
386       !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
387       FindAllocationFunctions(StartLoc,
388                               SourceRange(PlacementLParen, PlacementRParen),
389                               UseGlobal, AllocType, ArraySize, PlaceArgs,
390                               NumPlaceArgs, OperatorNew, OperatorDelete))
391     return ExprError();
392 
393   bool Init = ConstructorLParen.isValid();
394   // --- Choosing a constructor ---
395   // C++ 5.3.4p15
396   // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
397   //   the object is not initialized. If the object, or any part of it, is
398   //   const-qualified, it's an error.
399   // 2) If T is a POD and there's an empty initializer, the object is value-
400   //   initialized.
401   // 3) If T is a POD and there's one initializer argument, the object is copy-
402   //   constructed.
403   // 4) If T is a POD and there's more initializer arguments, it's an error.
404   // 5) If T is not a POD, the initializer arguments are used as constructor
405   //   arguments.
406   //
407   // Or by the C++0x formulation:
408   // 1) If there's no initializer, the object is default-initialized according
409   //    to C++0x rules.
410   // 2) Otherwise, the object is direct-initialized.
411   CXXConstructorDecl *Constructor = 0;
412   Expr **ConsArgs = (Expr**)ConstructorArgs.get();
413   const RecordType *RT;
414   unsigned NumConsArgs = ConstructorArgs.size();
415   if (AllocType->isDependentType()) {
416     // Skip all the checks.
417   }
418   else if ((RT = AllocType->getAs<RecordType>()) &&
419             !AllocType->isAggregateType()) {
420     Constructor = PerformInitializationByConstructor(
421                       AllocType, ConsArgs, NumConsArgs,
422                       TypeLoc,
423                       SourceRange(TypeLoc, ConstructorRParen),
424                       RT->getDecl()->getDeclName(),
425                       NumConsArgs != 0 ? IK_Direct : IK_Default);
426     if (!Constructor)
427       return ExprError();
428   } else {
429     if (!Init) {
430       // FIXME: Check that no subpart is const.
431       if (AllocType.isConstQualified())
432         return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
433                            << TypeRange);
434     } else if (NumConsArgs == 0) {
435       // Object is value-initialized. Do nothing.
436     } else if (NumConsArgs == 1) {
437       // Object is direct-initialized.
438       // FIXME: What DeclarationName do we pass in here?
439       if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
440                                 DeclarationName() /*AllocType.getAsString()*/,
441                                 /*DirectInit=*/true))
442         return ExprError();
443     } else {
444       return ExprError(Diag(StartLoc,
445                             diag::err_builtin_direct_init_more_than_one_arg)
446         << SourceRange(ConstructorLParen, ConstructorRParen));
447     }
448   }
449 
450   // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
451 
452   PlacementArgs.release();
453   ConstructorArgs.release();
454   ArraySizeE.release();
455   return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
456                         NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
457                         ConsArgs, NumConsArgs, OperatorDelete, ResultType,
458                         StartLoc, Init ? ConstructorRParen : SourceLocation()));
459 }
460 
461 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
462 /// in a new-expression.
463 /// dimension off and stores the size expression in ArraySize.
464 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
465                               SourceRange R)
466 {
467   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
468   //   abstract class type or array thereof.
469   if (AllocType->isFunctionType())
470     return Diag(Loc, diag::err_bad_new_type)
471       << AllocType << 0 << R;
472   else if (AllocType->isReferenceType())
473     return Diag(Loc, diag::err_bad_new_type)
474       << AllocType << 1 << R;
475   else if (!AllocType->isDependentType() &&
476            RequireCompleteType(Loc, AllocType,
477                                diag::err_new_incomplete_type,
478                                R))
479     return true;
480   else if (RequireNonAbstractType(Loc, AllocType,
481                                   diag::err_allocation_of_abstract_type))
482     return true;
483 
484   return false;
485 }
486 
487 /// FindAllocationFunctions - Finds the overloads of operator new and delete
488 /// that are appropriate for the allocation.
489 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
490                                    bool UseGlobal, QualType AllocType,
491                                    bool IsArray, Expr **PlaceArgs,
492                                    unsigned NumPlaceArgs,
493                                    FunctionDecl *&OperatorNew,
494                                    FunctionDecl *&OperatorDelete)
495 {
496   // --- Choosing an allocation function ---
497   // C++ 5.3.4p8 - 14 & 18
498   // 1) If UseGlobal is true, only look in the global scope. Else, also look
499   //   in the scope of the allocated class.
500   // 2) If an array size is given, look for operator new[], else look for
501   //   operator new.
502   // 3) The first argument is always size_t. Append the arguments from the
503   //   placement form.
504   // FIXME: Also find the appropriate delete operator.
505 
506   llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
507   // We don't care about the actual value of this argument.
508   // FIXME: Should the Sema create the expression and embed it in the syntax
509   // tree? Or should the consumer just recalculate the value?
510   AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
511                                         Context.Target.getPointerWidth(0)),
512                                     Context.getSizeType(),
513                                     SourceLocation());
514   std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
515 
516   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
517                                         IsArray ? OO_Array_New : OO_New);
518   if (AllocType->isRecordType() && !UseGlobal) {
519     CXXRecordDecl *Record
520       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
521     // FIXME: We fail to find inherited overloads.
522     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
523                           AllocArgs.size(), Record, /*AllowMissing=*/true,
524                           OperatorNew))
525       return true;
526   }
527   if (!OperatorNew) {
528     // Didn't find a member overload. Look for a global one.
529     DeclareGlobalNewDelete();
530     DeclContext *TUDecl = Context.getTranslationUnitDecl();
531     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
532                           AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
533                           OperatorNew))
534       return true;
535   }
536 
537   // FindAllocationOverload can change the passed in arguments, so we need to
538   // copy them back.
539   if (NumPlaceArgs > 0)
540     std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
541 
542   // FIXME: This is leaked on error. But so much is currently in Sema that it's
543   // easier to clean it in one go.
544   AllocArgs[0]->Destroy(Context);
545   return false;
546 }
547 
548 /// FindAllocationOverload - Find an fitting overload for the allocation
549 /// function in the specified scope.
550 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
551                                   DeclarationName Name, Expr** Args,
552                                   unsigned NumArgs, DeclContext *Ctx,
553                                   bool AllowMissing, FunctionDecl *&Operator)
554 {
555   DeclContext::lookup_iterator Alloc, AllocEnd;
556   llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
557   if (Alloc == AllocEnd) {
558     if (AllowMissing)
559       return false;
560     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
561       << Name << Range;
562   }
563 
564   OverloadCandidateSet Candidates;
565   for (; Alloc != AllocEnd; ++Alloc) {
566     // Even member operator new/delete are implicitly treated as
567     // static, so don't use AddMemberCandidate.
568     if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
569       AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
570                            /*SuppressUserConversions=*/false);
571   }
572 
573   // Do the resolution.
574   OverloadCandidateSet::iterator Best;
575   switch(BestViableFunction(Candidates, StartLoc, Best)) {
576   case OR_Success: {
577     // Got one!
578     FunctionDecl *FnDecl = Best->Function;
579     // The first argument is size_t, and the first parameter must be size_t,
580     // too. This is checked on declaration and can be assumed. (It can't be
581     // asserted on, though, since invalid decls are left in there.)
582     for (unsigned i = 1; i < NumArgs; ++i) {
583       // FIXME: Passing word to diagnostic.
584       if (PerformCopyInitialization(Args[i],
585                                     FnDecl->getParamDecl(i)->getType(),
586                                     "passing"))
587         return true;
588     }
589     Operator = FnDecl;
590     return false;
591   }
592 
593   case OR_No_Viable_Function:
594     Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
595       << Name << Range;
596     PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
597     return true;
598 
599   case OR_Ambiguous:
600     Diag(StartLoc, diag::err_ovl_ambiguous_call)
601       << Name << Range;
602     PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
603     return true;
604 
605   case OR_Deleted:
606     Diag(StartLoc, diag::err_ovl_deleted_call)
607       << Best->Function->isDeleted()
608       << Name << Range;
609     PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
610     return true;
611   }
612   assert(false && "Unreachable, bad result from BestViableFunction");
613   return true;
614 }
615 
616 
617 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
618 /// delete. These are:
619 /// @code
620 ///   void* operator new(std::size_t) throw(std::bad_alloc);
621 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
622 ///   void operator delete(void *) throw();
623 ///   void operator delete[](void *) throw();
624 /// @endcode
625 /// Note that the placement and nothrow forms of new are *not* implicitly
626 /// declared. Their use requires including \<new\>.
627 void Sema::DeclareGlobalNewDelete()
628 {
629   if (GlobalNewDeleteDeclared)
630     return;
631   GlobalNewDeleteDeclared = true;
632 
633   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
634   QualType SizeT = Context.getSizeType();
635 
636   // FIXME: Exception specifications are not added.
637   DeclareGlobalAllocationFunction(
638       Context.DeclarationNames.getCXXOperatorName(OO_New),
639       VoidPtr, SizeT);
640   DeclareGlobalAllocationFunction(
641       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
642       VoidPtr, SizeT);
643   DeclareGlobalAllocationFunction(
644       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
645       Context.VoidTy, VoidPtr);
646   DeclareGlobalAllocationFunction(
647       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
648       Context.VoidTy, VoidPtr);
649 }
650 
651 /// DeclareGlobalAllocationFunction - Declares a single implicit global
652 /// allocation function if it doesn't already exist.
653 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
654                                            QualType Return, QualType Argument)
655 {
656   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
657 
658   // Check if this function is already declared.
659   {
660     DeclContext::lookup_iterator Alloc, AllocEnd;
661     for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
662          Alloc != AllocEnd; ++Alloc) {
663       // FIXME: Do we need to check for default arguments here?
664       FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
665       if (Func->getNumParams() == 1 &&
666           Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
667         return;
668     }
669   }
670 
671   QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
672   FunctionDecl *Alloc =
673     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
674                          FnType, FunctionDecl::None, false, true,
675                          SourceLocation());
676   Alloc->setImplicit();
677   ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
678                                            0, Argument, VarDecl::None, 0);
679   Alloc->setParams(Context, &Param, 1);
680 
681   // FIXME: Also add this declaration to the IdentifierResolver, but
682   // make sure it is at the end of the chain to coincide with the
683   // global scope.
684   ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
685 }
686 
687 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
688 /// @code ::delete ptr; @endcode
689 /// or
690 /// @code delete [] ptr; @endcode
691 Action::OwningExprResult
692 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
693                      bool ArrayForm, ExprArg Operand)
694 {
695   // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
696   //   having a single conversion function to a pointer type. The result has
697   //   type void."
698   // DR599 amends "pointer type" to "pointer to object type" in both cases.
699 
700   Expr *Ex = (Expr *)Operand.get();
701   if (!Ex->isTypeDependent()) {
702     QualType Type = Ex->getType();
703 
704     if (Type->isRecordType()) {
705       // FIXME: Find that one conversion function and amend the type.
706     }
707 
708     if (!Type->isPointerType())
709       return ExprError(Diag(StartLoc, diag::err_delete_operand)
710         << Type << Ex->getSourceRange());
711 
712     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
713     if (Pointee->isFunctionType() || Pointee->isVoidType())
714       return ExprError(Diag(StartLoc, diag::err_delete_operand)
715         << Type << Ex->getSourceRange());
716     else if (!Pointee->isDependentType() &&
717              RequireCompleteType(StartLoc, Pointee,
718                                  diag::warn_delete_incomplete,
719                                  Ex->getSourceRange()))
720       return ExprError();
721 
722     // FIXME: Look up the correct operator delete overload and pass a pointer
723     // along.
724     // FIXME: Check access and ambiguity of operator delete and destructor.
725   }
726 
727   Operand.release();
728   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
729                                            0, Ex, StartLoc));
730 }
731 
732 
733 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
734 /// C++ if/switch/while/for statement.
735 /// e.g: "if (int x = f()) {...}"
736 Action::OwningExprResult
737 Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
738                                        Declarator &D,
739                                        SourceLocation EqualLoc,
740                                        ExprArg AssignExprVal) {
741   assert(AssignExprVal.get() && "Null assignment expression");
742 
743   // C++ 6.4p2:
744   // The declarator shall not specify a function or an array.
745   // The type-specifier-seq shall not contain typedef and shall not declare a
746   // new class or enumeration.
747 
748   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
749          "Parser allowed 'typedef' as storage class of condition decl.");
750 
751   QualType Ty = GetTypeForDeclarator(D, S);
752 
753   if (Ty->isFunctionType()) { // The declarator shall not specify a function...
754     // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
755     // would be created and CXXConditionDeclExpr wants a VarDecl.
756     return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
757       << SourceRange(StartLoc, EqualLoc));
758   } else if (Ty->isArrayType()) { // ...or an array.
759     Diag(StartLoc, diag::err_invalid_use_of_array_type)
760       << SourceRange(StartLoc, EqualLoc);
761   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
762     RecordDecl *RD = RT->getDecl();
763     // The type-specifier-seq shall not declare a new class...
764     if (RD->isDefinition() &&
765         (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
766       Diag(RD->getLocation(), diag::err_type_defined_in_condition);
767   } else if (const EnumType *ET = Ty->getAsEnumType()) {
768     EnumDecl *ED = ET->getDecl();
769     // ...or enumeration.
770     if (ED->isDefinition() &&
771         (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
772       Diag(ED->getLocation(), diag::err_type_defined_in_condition);
773   }
774 
775   DeclPtrTy Dcl = ActOnDeclarator(S, D);
776   if (!Dcl)
777     return ExprError();
778   AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
779 
780   // Mark this variable as one that is declared within a conditional.
781   // We know that the decl had to be a VarDecl because that is the only type of
782   // decl that can be assigned and the grammar requires an '='.
783   VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
784   VD->setDeclaredInCondition(true);
785   return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
786 }
787 
788 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
789 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
790   // C++ 6.4p4:
791   // The value of a condition that is an initialized declaration in a statement
792   // other than a switch statement is the value of the declared variable
793   // implicitly converted to type bool. If that conversion is ill-formed, the
794   // program is ill-formed.
795   // The value of a condition that is an expression is the value of the
796   // expression, implicitly converted to bool.
797   //
798   return PerformContextuallyConvertToBool(CondExpr);
799 }
800 
801 /// Helper function to determine whether this is the (deprecated) C++
802 /// conversion from a string literal to a pointer to non-const char or
803 /// non-const wchar_t (for narrow and wide string literals,
804 /// respectively).
805 bool
806 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
807   // Look inside the implicit cast, if it exists.
808   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
809     From = Cast->getSubExpr();
810 
811   // A string literal (2.13.4) that is not a wide string literal can
812   // be converted to an rvalue of type "pointer to char"; a wide
813   // string literal can be converted to an rvalue of type "pointer
814   // to wchar_t" (C++ 4.2p2).
815   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
816     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
817       if (const BuiltinType *ToPointeeType
818           = ToPtrType->getPointeeType()->getAsBuiltinType()) {
819         // This conversion is considered only when there is an
820         // explicit appropriate pointer target type (C++ 4.2p2).
821         if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
822             ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
823              (!StrLit->isWide() &&
824               (ToPointeeType->getKind() == BuiltinType::Char_U ||
825                ToPointeeType->getKind() == BuiltinType::Char_S))))
826           return true;
827       }
828 
829   return false;
830 }
831 
832 /// PerformImplicitConversion - Perform an implicit conversion of the
833 /// expression From to the type ToType. Returns true if there was an
834 /// error, false otherwise. The expression From is replaced with the
835 /// converted expression. Flavor is the kind of conversion we're
836 /// performing, used in the error message. If @p AllowExplicit,
837 /// explicit user-defined conversions are permitted. @p Elidable should be true
838 /// when called for copies which may be elided (C++ 12.8p15). C++0x overload
839 /// resolution works differently in that case.
840 bool
841 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
842                                 const char *Flavor, bool AllowExplicit,
843                                 bool Elidable)
844 {
845   ImplicitConversionSequence ICS;
846   ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
847   if (Elidable && getLangOptions().CPlusPlus0x) {
848     ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
849                                 AllowExplicit, /*ForceRValue*/true);
850   }
851   if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
852     ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
853   }
854   return PerformImplicitConversion(From, ToType, ICS, Flavor);
855 }
856 
857 /// PerformImplicitConversion - Perform an implicit conversion of the
858 /// expression From to the type ToType using the pre-computed implicit
859 /// conversion sequence ICS. Returns true if there was an error, false
860 /// otherwise. The expression From is replaced with the converted
861 /// expression. Flavor is the kind of conversion we're performing,
862 /// used in the error message.
863 bool
864 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
865                                 const ImplicitConversionSequence &ICS,
866                                 const char* Flavor) {
867   switch (ICS.ConversionKind) {
868   case ImplicitConversionSequence::StandardConversion:
869     if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
870       return true;
871     break;
872 
873   case ImplicitConversionSequence::UserDefinedConversion:
874     // FIXME: This is, of course, wrong. We'll need to actually call the
875     // constructor or conversion operator, and then cope with the standard
876     // conversions.
877     ImpCastExprToType(From, ToType.getNonReferenceType(),
878                       CastExpr::CK_Unknown,
879                       ToType->isLValueReferenceType());
880     return false;
881 
882   case ImplicitConversionSequence::EllipsisConversion:
883     assert(false && "Cannot perform an ellipsis conversion");
884     return false;
885 
886   case ImplicitConversionSequence::BadConversion:
887     return true;
888   }
889 
890   // Everything went well.
891   return false;
892 }
893 
894 /// PerformImplicitConversion - Perform an implicit conversion of the
895 /// expression From to the type ToType by following the standard
896 /// conversion sequence SCS. Returns true if there was an error, false
897 /// otherwise. The expression From is replaced with the converted
898 /// expression. Flavor is the context in which we're performing this
899 /// conversion, for use in error messages.
900 bool
901 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
902                                 const StandardConversionSequence& SCS,
903                                 const char *Flavor) {
904   // Overall FIXME: we are recomputing too many types here and doing far too
905   // much extra work. What this means is that we need to keep track of more
906   // information that is computed when we try the implicit conversion initially,
907   // so that we don't need to recompute anything here.
908   QualType FromType = From->getType();
909 
910   if (SCS.CopyConstructor) {
911     // FIXME: When can ToType be a reference type?
912     assert(!ToType->isReferenceType());
913 
914     // FIXME: Keep track of whether the copy constructor is elidable or not.
915     From = CXXConstructExpr::Create(Context, ToType,
916                                     SCS.CopyConstructor, false, &From, 1);
917     return false;
918   }
919 
920   // Perform the first implicit conversion.
921   switch (SCS.First) {
922   case ICK_Identity:
923   case ICK_Lvalue_To_Rvalue:
924     // Nothing to do.
925     break;
926 
927   case ICK_Array_To_Pointer:
928     FromType = Context.getArrayDecayedType(FromType);
929     ImpCastExprToType(From, FromType);
930     break;
931 
932   case ICK_Function_To_Pointer:
933     if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
934       FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
935       if (!Fn)
936         return true;
937 
938       if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
939         return true;
940 
941       FixOverloadedFunctionReference(From, Fn);
942       FromType = From->getType();
943     }
944     FromType = Context.getPointerType(FromType);
945     ImpCastExprToType(From, FromType);
946     break;
947 
948   default:
949     assert(false && "Improper first standard conversion");
950     break;
951   }
952 
953   // Perform the second implicit conversion
954   switch (SCS.Second) {
955   case ICK_Identity:
956     // Nothing to do.
957     break;
958 
959   case ICK_Integral_Promotion:
960   case ICK_Floating_Promotion:
961   case ICK_Complex_Promotion:
962   case ICK_Integral_Conversion:
963   case ICK_Floating_Conversion:
964   case ICK_Complex_Conversion:
965   case ICK_Floating_Integral:
966   case ICK_Complex_Real:
967   case ICK_Compatible_Conversion:
968       // FIXME: Go deeper to get the unqualified type!
969     FromType = ToType.getUnqualifiedType();
970     ImpCastExprToType(From, FromType);
971     break;
972 
973   case ICK_Pointer_Conversion:
974     if (SCS.IncompatibleObjC) {
975       // Diagnose incompatible Objective-C conversions
976       Diag(From->getSourceRange().getBegin(),
977            diag::ext_typecheck_convert_incompatible_pointer)
978         << From->getType() << ToType << Flavor
979         << From->getSourceRange();
980     }
981 
982     if (CheckPointerConversion(From, ToType))
983       return true;
984     ImpCastExprToType(From, ToType);
985     break;
986 
987   case ICK_Pointer_Member:
988     if (CheckMemberPointerConversion(From, ToType))
989       return true;
990     ImpCastExprToType(From, ToType);
991     break;
992 
993   case ICK_Boolean_Conversion:
994     FromType = Context.BoolTy;
995     ImpCastExprToType(From, FromType);
996     break;
997 
998   default:
999     assert(false && "Improper second standard conversion");
1000     break;
1001   }
1002 
1003   switch (SCS.Third) {
1004   case ICK_Identity:
1005     // Nothing to do.
1006     break;
1007 
1008   case ICK_Qualification:
1009     // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1010     // references.
1011     ImpCastExprToType(From, ToType.getNonReferenceType(),
1012                       CastExpr::CK_Unknown,
1013                       ToType->isLValueReferenceType());
1014     break;
1015 
1016   default:
1017     assert(false && "Improper second standard conversion");
1018     break;
1019   }
1020 
1021   return false;
1022 }
1023 
1024 Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1025                                                  SourceLocation KWLoc,
1026                                                  SourceLocation LParen,
1027                                                  TypeTy *Ty,
1028                                                  SourceLocation RParen) {
1029   QualType T = QualType::getFromOpaquePtr(Ty);
1030 
1031   // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1032   // all traits except __is_class, __is_enum and __is_union require a the type
1033   // to be complete.
1034   if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1035     if (RequireCompleteType(KWLoc, T,
1036                             diag::err_incomplete_type_used_in_type_trait_expr,
1037                             SourceRange(), SourceRange(), T))
1038       return ExprError();
1039   }
1040 
1041   // There is no point in eagerly computing the value. The traits are designed
1042   // to be used from type trait templates, so Ty will be a template parameter
1043   // 99% of the time.
1044   return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1045                                                 RParen, Context.BoolTy));
1046 }
1047 
1048 QualType Sema::CheckPointerToMemberOperands(
1049   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1050 {
1051   const char *OpSpelling = isIndirect ? "->*" : ".*";
1052   // C++ 5.5p2
1053   //   The binary operator .* [p3: ->*] binds its second operand, which shall
1054   //   be of type "pointer to member of T" (where T is a completely-defined
1055   //   class type) [...]
1056   QualType RType = rex->getType();
1057   const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1058   if (!MemPtr) {
1059     Diag(Loc, diag::err_bad_memptr_rhs)
1060       << OpSpelling << RType << rex->getSourceRange();
1061     return QualType();
1062   }
1063 
1064   QualType Class(MemPtr->getClass(), 0);
1065 
1066   // C++ 5.5p2
1067   //   [...] to its first operand, which shall be of class T or of a class of
1068   //   which T is an unambiguous and accessible base class. [p3: a pointer to
1069   //   such a class]
1070   QualType LType = lex->getType();
1071   if (isIndirect) {
1072     if (const PointerType *Ptr = LType->getAs<PointerType>())
1073       LType = Ptr->getPointeeType().getNonReferenceType();
1074     else {
1075       Diag(Loc, diag::err_bad_memptr_lhs)
1076         << OpSpelling << 1 << LType << lex->getSourceRange();
1077       return QualType();
1078     }
1079   }
1080 
1081   if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1082       Context.getCanonicalType(LType).getUnqualifiedType()) {
1083     BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1084                     /*DetectVirtual=*/false);
1085     // FIXME: Would it be useful to print full ambiguity paths, or is that
1086     // overkill?
1087     if (!IsDerivedFrom(LType, Class, Paths) ||
1088         Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1089       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1090         << (int)isIndirect << lex->getType() << lex->getSourceRange();
1091       return QualType();
1092     }
1093   }
1094 
1095   // C++ 5.5p2
1096   //   The result is an object or a function of the type specified by the
1097   //   second operand.
1098   // The cv qualifiers are the union of those in the pointer and the left side,
1099   // in accordance with 5.5p5 and 5.2.5.
1100   // FIXME: This returns a dereferenced member function pointer as a normal
1101   // function type. However, the only operation valid on such functions is
1102   // calling them. There's also a GCC extension to get a function pointer to the
1103   // thing, which is another complication, because this type - unlike the type
1104   // that is the result of this expression - takes the class as the first
1105   // argument.
1106   // We probably need a "MemberFunctionClosureType" or something like that.
1107   QualType Result = MemPtr->getPointeeType();
1108   if (LType.isConstQualified())
1109     Result.addConst();
1110   if (LType.isVolatileQualified())
1111     Result.addVolatile();
1112   return Result;
1113 }
1114 
1115 /// \brief Get the target type of a standard or user-defined conversion.
1116 static QualType TargetType(const ImplicitConversionSequence &ICS) {
1117   assert((ICS.ConversionKind ==
1118               ImplicitConversionSequence::StandardConversion ||
1119           ICS.ConversionKind ==
1120               ImplicitConversionSequence::UserDefinedConversion) &&
1121          "function only valid for standard or user-defined conversions");
1122   if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1123     return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1124   return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1125 }
1126 
1127 /// \brief Try to convert a type to another according to C++0x 5.16p3.
1128 ///
1129 /// This is part of the parameter validation for the ? operator. If either
1130 /// value operand is a class type, the two operands are attempted to be
1131 /// converted to each other. This function does the conversion in one direction.
1132 /// It emits a diagnostic and returns true only if it finds an ambiguous
1133 /// conversion.
1134 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1135                                 SourceLocation QuestionLoc,
1136                                 ImplicitConversionSequence &ICS)
1137 {
1138   // C++0x 5.16p3
1139   //   The process for determining whether an operand expression E1 of type T1
1140   //   can be converted to match an operand expression E2 of type T2 is defined
1141   //   as follows:
1142   //   -- If E2 is an lvalue:
1143   if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1144     //   E1 can be converted to match E2 if E1 can be implicitly converted to
1145     //   type "lvalue reference to T2", subject to the constraint that in the
1146     //   conversion the reference must bind directly to E1.
1147     if (!Self.CheckReferenceInit(From,
1148                             Self.Context.getLValueReferenceType(To->getType()),
1149                             &ICS))
1150     {
1151       assert((ICS.ConversionKind ==
1152                   ImplicitConversionSequence::StandardConversion ||
1153               ICS.ConversionKind ==
1154                   ImplicitConversionSequence::UserDefinedConversion) &&
1155              "expected a definite conversion");
1156       bool DirectBinding =
1157         ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1158         ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1159       if (DirectBinding)
1160         return false;
1161     }
1162   }
1163   ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1164   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1165   //      -- if E1 and E2 have class type, and the underlying class types are
1166   //         the same or one is a base class of the other:
1167   QualType FTy = From->getType();
1168   QualType TTy = To->getType();
1169   const RecordType *FRec = FTy->getAs<RecordType>();
1170   const RecordType *TRec = TTy->getAs<RecordType>();
1171   bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1172   if (FRec && TRec && (FRec == TRec ||
1173         FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1174     //         E1 can be converted to match E2 if the class of T2 is the
1175     //         same type as, or a base class of, the class of T1, and
1176     //         [cv2 > cv1].
1177     if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1178       // Could still fail if there's no copy constructor.
1179       // FIXME: Is this a hard error then, or just a conversion failure? The
1180       // standard doesn't say.
1181       ICS = Self.TryCopyInitialization(From, TTy);
1182     }
1183   } else {
1184     //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1185     //        implicitly converted to the type that expression E2 would have
1186     //        if E2 were converted to an rvalue.
1187     // First find the decayed type.
1188     if (TTy->isFunctionType())
1189       TTy = Self.Context.getPointerType(TTy);
1190     else if(TTy->isArrayType())
1191       TTy = Self.Context.getArrayDecayedType(TTy);
1192 
1193     // Now try the implicit conversion.
1194     // FIXME: This doesn't detect ambiguities.
1195     ICS = Self.TryImplicitConversion(From, TTy);
1196   }
1197   return false;
1198 }
1199 
1200 /// \brief Try to find a common type for two according to C++0x 5.16p5.
1201 ///
1202 /// This is part of the parameter validation for the ? operator. If either
1203 /// value operand is a class type, overload resolution is used to find a
1204 /// conversion to a common type.
1205 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1206                                     SourceLocation Loc) {
1207   Expr *Args[2] = { LHS, RHS };
1208   OverloadCandidateSet CandidateSet;
1209   Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1210 
1211   OverloadCandidateSet::iterator Best;
1212   switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1213     case Sema::OR_Success:
1214       // We found a match. Perform the conversions on the arguments and move on.
1215       if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1216                                          Best->Conversions[0], "converting") ||
1217           Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1218                                          Best->Conversions[1], "converting"))
1219         break;
1220       return false;
1221 
1222     case Sema::OR_No_Viable_Function:
1223       Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1224         << LHS->getType() << RHS->getType()
1225         << LHS->getSourceRange() << RHS->getSourceRange();
1226       return true;
1227 
1228     case Sema::OR_Ambiguous:
1229       Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1230         << LHS->getType() << RHS->getType()
1231         << LHS->getSourceRange() << RHS->getSourceRange();
1232       // FIXME: Print the possible common types by printing the return types of
1233       // the viable candidates.
1234       break;
1235 
1236     case Sema::OR_Deleted:
1237       assert(false && "Conditional operator has only built-in overloads");
1238       break;
1239   }
1240   return true;
1241 }
1242 
1243 /// \brief Perform an "extended" implicit conversion as returned by
1244 /// TryClassUnification.
1245 ///
1246 /// TryClassUnification generates ICSs that include reference bindings.
1247 /// PerformImplicitConversion is not suitable for this; it chokes if the
1248 /// second part of a standard conversion is ICK_DerivedToBase. This function
1249 /// handles the reference binding specially.
1250 static bool ConvertForConditional(Sema &Self, Expr *&E,
1251                                   const ImplicitConversionSequence &ICS)
1252 {
1253   if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1254       ICS.Standard.ReferenceBinding) {
1255     assert(ICS.Standard.DirectBinding &&
1256            "TryClassUnification should never generate indirect ref bindings");
1257     // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1258     // redoing all the work.
1259     return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1260                                         TargetType(ICS)));
1261   }
1262   if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1263       ICS.UserDefined.After.ReferenceBinding) {
1264     assert(ICS.UserDefined.After.DirectBinding &&
1265            "TryClassUnification should never generate indirect ref bindings");
1266     return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1267                                         TargetType(ICS)));
1268   }
1269   if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1270     return true;
1271   return false;
1272 }
1273 
1274 /// \brief Check the operands of ?: under C++ semantics.
1275 ///
1276 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1277 /// extension. In this case, LHS == Cond. (But they're not aliases.)
1278 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1279                                            SourceLocation QuestionLoc) {
1280   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1281   // interface pointers.
1282 
1283   // C++0x 5.16p1
1284   //   The first expression is contextually converted to bool.
1285   if (!Cond->isTypeDependent()) {
1286     if (CheckCXXBooleanCondition(Cond))
1287       return QualType();
1288   }
1289 
1290   // Either of the arguments dependent?
1291   if (LHS->isTypeDependent() || RHS->isTypeDependent())
1292     return Context.DependentTy;
1293 
1294   // C++0x 5.16p2
1295   //   If either the second or the third operand has type (cv) void, ...
1296   QualType LTy = LHS->getType();
1297   QualType RTy = RHS->getType();
1298   bool LVoid = LTy->isVoidType();
1299   bool RVoid = RTy->isVoidType();
1300   if (LVoid || RVoid) {
1301     //   ... then the [l2r] conversions are performed on the second and third
1302     //   operands ...
1303     DefaultFunctionArrayConversion(LHS);
1304     DefaultFunctionArrayConversion(RHS);
1305     LTy = LHS->getType();
1306     RTy = RHS->getType();
1307 
1308     //   ... and one of the following shall hold:
1309     //   -- The second or the third operand (but not both) is a throw-
1310     //      expression; the result is of the type of the other and is an rvalue.
1311     bool LThrow = isa<CXXThrowExpr>(LHS);
1312     bool RThrow = isa<CXXThrowExpr>(RHS);
1313     if (LThrow && !RThrow)
1314       return RTy;
1315     if (RThrow && !LThrow)
1316       return LTy;
1317 
1318     //   -- Both the second and third operands have type void; the result is of
1319     //      type void and is an rvalue.
1320     if (LVoid && RVoid)
1321       return Context.VoidTy;
1322 
1323     // Neither holds, error.
1324     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1325       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1326       << LHS->getSourceRange() << RHS->getSourceRange();
1327     return QualType();
1328   }
1329 
1330   // Neither is void.
1331 
1332   // C++0x 5.16p3
1333   //   Otherwise, if the second and third operand have different types, and
1334   //   either has (cv) class type, and attempt is made to convert each of those
1335   //   operands to the other.
1336   if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1337       (LTy->isRecordType() || RTy->isRecordType())) {
1338     ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1339     // These return true if a single direction is already ambiguous.
1340     if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1341       return QualType();
1342     if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1343       return QualType();
1344 
1345     bool HaveL2R = ICSLeftToRight.ConversionKind !=
1346       ImplicitConversionSequence::BadConversion;
1347     bool HaveR2L = ICSRightToLeft.ConversionKind !=
1348       ImplicitConversionSequence::BadConversion;
1349     //   If both can be converted, [...] the program is ill-formed.
1350     if (HaveL2R && HaveR2L) {
1351       Diag(QuestionLoc, diag::err_conditional_ambiguous)
1352         << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1353       return QualType();
1354     }
1355 
1356     //   If exactly one conversion is possible, that conversion is applied to
1357     //   the chosen operand and the converted operands are used in place of the
1358     //   original operands for the remainder of this section.
1359     if (HaveL2R) {
1360       if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1361         return QualType();
1362       LTy = LHS->getType();
1363     } else if (HaveR2L) {
1364       if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1365         return QualType();
1366       RTy = RHS->getType();
1367     }
1368   }
1369 
1370   // C++0x 5.16p4
1371   //   If the second and third operands are lvalues and have the same type,
1372   //   the result is of that type [...]
1373   bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1374   if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1375       RHS->isLvalue(Context) == Expr::LV_Valid)
1376     return LTy;
1377 
1378   // C++0x 5.16p5
1379   //   Otherwise, the result is an rvalue. If the second and third operands
1380   //   do not have the same type, and either has (cv) class type, ...
1381   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1382     //   ... overload resolution is used to determine the conversions (if any)
1383     //   to be applied to the operands. If the overload resolution fails, the
1384     //   program is ill-formed.
1385     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1386       return QualType();
1387   }
1388 
1389   // C++0x 5.16p6
1390   //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1391   //   conversions are performed on the second and third operands.
1392   DefaultFunctionArrayConversion(LHS);
1393   DefaultFunctionArrayConversion(RHS);
1394   LTy = LHS->getType();
1395   RTy = RHS->getType();
1396 
1397   //   After those conversions, one of the following shall hold:
1398   //   -- The second and third operands have the same type; the result
1399   //      is of that type.
1400   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1401     return LTy;
1402 
1403   //   -- The second and third operands have arithmetic or enumeration type;
1404   //      the usual arithmetic conversions are performed to bring them to a
1405   //      common type, and the result is of that type.
1406   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1407     UsualArithmeticConversions(LHS, RHS);
1408     return LHS->getType();
1409   }
1410 
1411   //   -- The second and third operands have pointer type, or one has pointer
1412   //      type and the other is a null pointer constant; pointer conversions
1413   //      and qualification conversions are performed to bring them to their
1414   //      composite pointer type. The result is of the composite pointer type.
1415   QualType Composite = FindCompositePointerType(LHS, RHS);
1416   if (!Composite.isNull())
1417     return Composite;
1418 
1419   // Fourth bullet is same for pointers-to-member. However, the possible
1420   // conversions are far more limited: we have null-to-pointer, upcast of
1421   // containing class, and second-level cv-ness.
1422   // cv-ness is not a union, but must match one of the two operands. (Which,
1423   // frankly, is stupid.)
1424   const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1425   const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1426   if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1427     ImpCastExprToType(RHS, LTy);
1428     return LTy;
1429   }
1430   if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1431     ImpCastExprToType(LHS, RTy);
1432     return RTy;
1433   }
1434   if (LMemPtr && RMemPtr) {
1435     QualType LPointee = LMemPtr->getPointeeType();
1436     QualType RPointee = RMemPtr->getPointeeType();
1437     // First, we check that the unqualified pointee type is the same. If it's
1438     // not, there's no conversion that will unify the two pointers.
1439     if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1440         Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1441       // Second, we take the greater of the two cv qualifications. If neither
1442       // is greater than the other, the conversion is not possible.
1443       unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1444       if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1445         // Third, we check if either of the container classes is derived from
1446         // the other.
1447         QualType LContainer(LMemPtr->getClass(), 0);
1448         QualType RContainer(RMemPtr->getClass(), 0);
1449         QualType MoreDerived;
1450         if (Context.getCanonicalType(LContainer) ==
1451             Context.getCanonicalType(RContainer))
1452           MoreDerived = LContainer;
1453         else if (IsDerivedFrom(LContainer, RContainer))
1454           MoreDerived = LContainer;
1455         else if (IsDerivedFrom(RContainer, LContainer))
1456           MoreDerived = RContainer;
1457 
1458         if (!MoreDerived.isNull()) {
1459           // The type 'Q Pointee (MoreDerived::*)' is the common type.
1460           // We don't use ImpCastExprToType here because this could still fail
1461           // for ambiguous or inaccessible conversions.
1462           QualType Common = Context.getMemberPointerType(
1463             LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1464           if (PerformImplicitConversion(LHS, Common, "converting"))
1465             return QualType();
1466           if (PerformImplicitConversion(RHS, Common, "converting"))
1467             return QualType();
1468           return Common;
1469         }
1470       }
1471     }
1472   }
1473 
1474   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1475     << LHS->getType() << RHS->getType()
1476     << LHS->getSourceRange() << RHS->getSourceRange();
1477   return QualType();
1478 }
1479 
1480 /// \brief Find a merged pointer type and convert the two expressions to it.
1481 ///
1482 /// This finds the composite pointer type for @p E1 and @p E2 according to
1483 /// C++0x 5.9p2. It converts both expressions to this type and returns it.
1484 /// It does not emit diagnostics.
1485 QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1486   assert(getLangOptions().CPlusPlus && "This function assumes C++");
1487   QualType T1 = E1->getType(), T2 = E2->getType();
1488   if(!T1->isAnyPointerType() && !T2->isAnyPointerType())
1489     return QualType();
1490 
1491   // C++0x 5.9p2
1492   //   Pointer conversions and qualification conversions are performed on
1493   //   pointer operands to bring them to their composite pointer type. If
1494   //   one operand is a null pointer constant, the composite pointer type is
1495   //   the type of the other operand.
1496   if (E1->isNullPointerConstant(Context)) {
1497     ImpCastExprToType(E1, T2);
1498     return T2;
1499   }
1500   if (E2->isNullPointerConstant(Context)) {
1501     ImpCastExprToType(E2, T1);
1502     return T1;
1503   }
1504   // Now both have to be pointers.
1505   if(!T1->isPointerType() || !T2->isPointerType())
1506     return QualType();
1507 
1508   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1509   //   the other has type "pointer to cv2 T" and the composite pointer type is
1510   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1511   //   Otherwise, the composite pointer type is a pointer type similar to the
1512   //   type of one of the operands, with a cv-qualification signature that is
1513   //   the union of the cv-qualification signatures of the operand types.
1514   // In practice, the first part here is redundant; it's subsumed by the second.
1515   // What we do here is, we build the two possible composite types, and try the
1516   // conversions in both directions. If only one works, or if the two composite
1517   // types are the same, we have succeeded.
1518   llvm::SmallVector<unsigned, 4> QualifierUnion;
1519   QualType Composite1 = T1, Composite2 = T2;
1520   const PointerType *Ptr1, *Ptr2;
1521   while ((Ptr1 = Composite1->getAs<PointerType>()) &&
1522          (Ptr2 = Composite2->getAs<PointerType>())) {
1523     Composite1 = Ptr1->getPointeeType();
1524     Composite2 = Ptr2->getPointeeType();
1525     QualifierUnion.push_back(
1526       Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1527   }
1528   // Rewrap the composites as pointers with the union CVRs.
1529   for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1530        E = QualifierUnion.end(); I != E; ++I) {
1531     Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1532     Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1533   }
1534 
1535   ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1536   ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1537   ImplicitConversionSequence E1ToC2, E2ToC2;
1538   E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1539   E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1540   if (Context.getCanonicalType(Composite1) !=
1541       Context.getCanonicalType(Composite2)) {
1542     E1ToC2 = TryImplicitConversion(E1, Composite2);
1543     E2ToC2 = TryImplicitConversion(E2, Composite2);
1544   }
1545 
1546   bool ToC1Viable = E1ToC1.ConversionKind !=
1547                       ImplicitConversionSequence::BadConversion
1548                  && E2ToC1.ConversionKind !=
1549                       ImplicitConversionSequence::BadConversion;
1550   bool ToC2Viable = E1ToC2.ConversionKind !=
1551                       ImplicitConversionSequence::BadConversion
1552                  && E2ToC2.ConversionKind !=
1553                       ImplicitConversionSequence::BadConversion;
1554   if (ToC1Viable && !ToC2Viable) {
1555     if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1556         !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1557       return Composite1;
1558   }
1559   if (ToC2Viable && !ToC1Viable) {
1560     if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1561         !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1562       return Composite2;
1563   }
1564   return QualType();
1565 }
1566 
1567 Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1568   const RecordType *RT = E->getType()->getAs<RecordType>();
1569   if (!RT)
1570     return Owned(E);
1571 
1572   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1573   if (RD->hasTrivialDestructor())
1574     return Owned(E);
1575 
1576   CXXTemporary *Temp = CXXTemporary::Create(Context,
1577                                             RD->getDestructor(Context));
1578   ExprTemporaries.push_back(Temp);
1579   if (CXXDestructorDecl *Destructor =
1580         const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1581     MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1582   // FIXME: Add the temporary to the temporaries vector.
1583   return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1584 }
1585 
1586 Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1587                                               bool ShouldDestroyTemps) {
1588   assert(SubExpr && "sub expression can't be null!");
1589 
1590   if (ExprTemporaries.empty())
1591     return SubExpr;
1592 
1593   Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1594                                            &ExprTemporaries[0],
1595                                            ExprTemporaries.size(),
1596                                            ShouldDestroyTemps);
1597   ExprTemporaries.clear();
1598 
1599   return E;
1600 }
1601 
1602 Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1603   Expr *FullExpr = Arg.takeAs<Expr>();
1604   if (FullExpr)
1605     FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1606                                                  /*ShouldDestroyTemps=*/true);
1607 
1608   return Owned(FullExpr);
1609 }
1610