blob: d2122a45aecda392fc313d8c6bf8116ca984ecc0 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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//
Sebastian Redl9c618092011-07-14 19:08:10 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000025#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000026using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000027
Chris Lattner0cb78032009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
John McCall66884dd2011-02-21 07:22:22 +000032static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
33 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000034 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
35 return 0;
36
Chris Lattnera9196812009-02-26 23:26:43 +000037 // See if this is a string literal or @encode.
38 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000039
Chris Lattnera9196812009-02-26 23:26:43 +000040 // Handle @encode, which is a narrow string.
41 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
42 return Init;
43
44 // Otherwise we can only handle string literals.
45 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000046 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000047
48 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000049 // char array can be initialized with a narrow string.
50 // Only allow char x[] = "foo"; not char x[] = L"foo";
51 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000052 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000053
Eli Friedman42a84652009-05-31 10:54:53 +000054 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
55 // correction from DR343): "An array with element type compatible with a
56 // qualified or unqualified version of wchar_t may be initialized by a wide
57 // string literal, optionally enclosed in braces."
58 if (Context.typesAreCompatible(Context.getWCharType(),
59 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000060 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattner0cb78032009-02-24 22:27:37 +000062 return 0;
63}
64
John McCall66884dd2011-02-21 07:22:22 +000065static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
66 const ArrayType *arrayType = Context.getAsArrayType(declType);
67 if (!arrayType) return 0;
68
69 return IsStringInit(init, arrayType, Context);
70}
71
John McCall5decec92011-02-21 07:57:55 +000072static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
73 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000074 // Get the length of the string as parsed.
75 uint64_t StrLength =
76 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
77
Mike Stump11289f42009-09-09 15:08:12 +000078
Chris Lattner0cb78032009-02-24 22:27:37 +000079 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000080 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000081 // being initialized to a string literal.
82 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000083 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000084 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000085 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
86 ConstVal,
87 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000088 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000089 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Eli Friedman893abe42009-05-29 18:22:49 +000091 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000092
Eli Friedman554eba92011-04-11 00:23:45 +000093 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000094 // the size may be smaller or larger than the string we are initializing.
95 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000096 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +000097 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
98 // For Pascal strings it's OK to strip off the terminating null character,
99 // so the example below is valid:
100 //
101 // unsigned char a[2] = "\pa";
102 if (SL->isPascal())
103 StrLength--;
104 }
105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // [dcl.init.string]p2
107 if (StrLength > CAT->getSize().getZExtValue())
108 S.Diag(Str->getSourceRange().getBegin(),
109 diag::err_initializer_string_for_char_array_too_long)
110 << Str->getSourceRange();
111 } else {
112 // C99 6.7.8p14.
113 if (StrLength-1 > CAT->getSize().getZExtValue())
114 S.Diag(Str->getSourceRange().getBegin(),
115 diag::warn_initializer_string_for_char_array_too_long)
116 << Str->getSourceRange();
117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Eli Friedman893abe42009-05-29 18:22:49 +0000119 // Set the type to the actual size that we are initializing. If we have
120 // something like:
121 // char x[1] = "foo";
122 // then this will set the string literal's type to char[1].
123 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000124}
125
Chris Lattner0cb78032009-02-24 22:27:37 +0000126//===----------------------------------------------------------------------===//
127// Semantic checking for initializer lists.
128//===----------------------------------------------------------------------===//
129
Douglas Gregorcde232f2009-01-29 01:05:33 +0000130/// @brief Semantic checking for initializer lists.
131///
132/// The InitListChecker class contains a set of routines that each
133/// handle the initialization of a certain kind of entity, e.g.,
134/// arrays, vectors, struct/union types, scalars, etc. The
135/// InitListChecker itself performs a recursive walk of the subobject
136/// structure of the type to be initialized, while stepping through
137/// the initializer list one element at a time. The IList and Index
138/// parameters to each of the Check* routines contain the active
139/// (syntactic) initializer list and the index into that initializer
140/// list that represents the current initializer. Each routine is
141/// responsible for moving that Index forward as it consumes elements.
142///
143/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000144/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000145/// initializer list and the index into that initializer list where we
146/// are copying initializers as we map them over to the semantic
147/// list. Once we have completed our recursive walk of the subobject
148/// structure, we will have constructed a full semantic initializer
149/// list.
150///
151/// C99 designators cause changes in the initializer list traversal,
152/// because they make the initialization "jump" into a specific
153/// subobject and then continue the initialization from that
154/// point. CheckDesignatedInitializer() recursively steps into the
155/// designated subobject and manages backing out the recursion to
156/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000157namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000158class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000159 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000160 bool hadError;
161 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
162 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000163
Anders Carlsson6cabf312010-01-23 23:23:01 +0000164 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000165 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000166 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000167 unsigned &StructuredIndex,
168 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000169 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000170 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000171 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000172 unsigned &StructuredIndex,
173 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000174 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000175 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000176 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000177 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000179 unsigned &StructuredIndex,
180 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000183 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
185 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
190 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000191 void CheckReferenceType(const InitializedEntity &Entity,
192 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000193 unsigned &Index,
194 InitListExpr *StructuredList,
195 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000196 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000197 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000200 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000201 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000202 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000204 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000205 unsigned &StructuredIndex,
206 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000207 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000208 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000209 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000210 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000213 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000214 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000215 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000216 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000217 RecordDecl::field_iterator *NextField,
218 llvm::APSInt *NextElementIndex,
219 unsigned &Index,
220 InitListExpr *StructuredList,
221 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000222 bool FinishSubobjectInit,
223 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
225 QualType CurrentObjectType,
226 InitListExpr *StructuredList,
227 unsigned StructuredIndex,
228 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000229 void UpdateStructuredListElement(InitListExpr *StructuredList,
230 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000231 Expr *expr);
232 int numArrayElements(QualType DeclType);
233 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000234
Douglas Gregor2bb07652009-12-22 00:05:34 +0000235 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
236 const InitializedEntity &ParentEntity,
237 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000238 void FillInValueInitializations(const InitializedEntity &Entity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000241 InitListChecker(Sema &S, const InitializedEntity &Entity,
242 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 bool HadError() { return hadError; }
244
245 // @brief Retrieves the fully-structured initializer list used for
246 // semantic analysis and code generation.
247 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
248};
Chris Lattner9ececce2009-02-24 22:48:58 +0000249} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000250
Douglas Gregor2bb07652009-12-22 00:05:34 +0000251void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000253 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254 bool &RequiresSecondPass) {
255 SourceLocation Loc = ILE->getSourceRange().getBegin();
256 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000257 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000258 = InitializedEntity::InitializeMember(Field, &ParentEntity);
259 if (Init >= NumInits || !ILE->getInit(Init)) {
260 // FIXME: We probably don't need to handle references
261 // specially here, since value-initialization of references is
262 // handled in InitializationSequence.
263 if (Field->getType()->isReferenceType()) {
264 // C++ [dcl.init.aggr]p9:
265 // If an incomplete or empty initializer-list leaves a
266 // member of reference type uninitialized, the program is
267 // ill-formed.
268 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
269 << Field->getType()
270 << ILE->getSyntacticForm()->getSourceRange();
271 SemaRef.Diag(Field->getLocation(),
272 diag::note_uninit_reference_member);
273 hadError = true;
274 return;
275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Douglas Gregor2bb07652009-12-22 00:05:34 +0000277 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
278 true);
279 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
280 if (!InitSeq) {
281 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
282 hadError = true;
283 return;
284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
John McCalldadc5752010-08-24 06:29:42 +0000286 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000287 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288 if (MemberInit.isInvalid()) {
289 hadError = true;
290 return;
291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292
Douglas Gregor2bb07652009-12-22 00:05:34 +0000293 if (hadError) {
294 // Do nothing
295 } else if (Init < NumInits) {
296 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000297 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000298 // Value-initialization requires a constructor call, so
299 // extend the initializer list to include the constructor
300 // call and make a note that we'll need to take another pass
301 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000302 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000303 RequiresSecondPass = true;
304 }
305 } else if (InitListExpr *InnerILE
306 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000307 FillInValueInitializations(MemberEntity, InnerILE,
308 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000309}
310
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000311/// Recursively replaces NULL values within the given initializer list
312/// with expressions that perform value-initialization of the
313/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000314void
Douglas Gregor723796a2009-12-16 06:35:08 +0000315InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
316 InitListExpr *ILE,
317 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000318 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000319 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000320 SourceLocation Loc = ILE->getSourceRange().getBegin();
321 if (ILE->getSyntacticForm())
322 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000323
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000324 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 if (RType->getDecl()->isUnion() &&
326 ILE->getInitializedFieldInUnion())
327 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
328 Entity, ILE, RequiresSecondPass);
329 else {
330 unsigned Init = 0;
331 for (RecordDecl::field_iterator
332 Field = RType->getDecl()->field_begin(),
333 FieldEnd = RType->getDecl()->field_end();
334 Field != FieldEnd; ++Field) {
335 if (Field->isUnnamedBitfield())
336 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000337
Douglas Gregor2bb07652009-12-22 00:05:34 +0000338 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000339 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340
341 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
342 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000343 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000344
Douglas Gregor2bb07652009-12-22 00:05:34 +0000345 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000346
Douglas Gregor2bb07652009-12-22 00:05:34 +0000347 // Only look at the first initialization of a union.
348 if (RType->getDecl()->isUnion())
349 break;
350 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000351 }
352
353 return;
Mike Stump11289f42009-09-09 15:08:12 +0000354 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355
356 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000357
Douglas Gregor723796a2009-12-16 06:35:08 +0000358 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000359 unsigned NumInits = ILE->getNumInits();
360 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000361 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000362 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000363 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
364 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000366 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000367 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000368 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000369 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000370 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000371 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000372 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000373 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000374
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000375
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000377 if (hadError)
378 return;
379
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000380 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
381 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000382 ElementEntity.setElementIndex(Init);
383
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000384 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
386 true);
387 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
388 if (!InitSeq) {
389 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000390 hadError = true;
391 return;
392 }
393
John McCalldadc5752010-08-24 06:29:42 +0000394 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000395 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000396 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000397 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 return;
399 }
400
401 if (hadError) {
402 // Do nothing
403 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000404 // For arrays, just set the expression used for value-initialization
405 // of the "holes" in the array.
406 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
407 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
408 else
409 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000410 } else {
411 // For arrays, just set the expression used for value-initialization
412 // of the rest of elements and exit.
413 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
414 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
415 return;
416 }
417
Sebastian Redld201edf2011-06-05 13:59:11 +0000418 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000419 // Value-initialization requires a constructor call, so
420 // extend the initializer list to include the constructor
421 // call and make a note that we'll need to take another pass
422 // through the initializer list.
423 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
424 RequiresSecondPass = true;
425 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000426 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000427 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000428 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
429 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000430 }
431}
432
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000433
Douglas Gregor723796a2009-12-16 06:35:08 +0000434InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
435 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000436 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000437 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000438
Eli Friedman23a9e312008-05-19 19:16:24 +0000439 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000440 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000441 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000442 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000443 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000444 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000445 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000446
Douglas Gregor723796a2009-12-16 06:35:08 +0000447 if (!hadError) {
448 bool RequiresSecondPass = false;
449 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000450 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000452 RequiresSecondPass);
453 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000454}
455
456int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000457 // FIXME: use a proper constant
458 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000459 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000460 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000461 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
462 }
463 return maxElements;
464}
465
466int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000467 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000470 Field = structDecl->field_begin(),
471 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000472 Field != FieldEnd; ++Field) {
473 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
474 ++InitializableMembers;
475 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000476 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000477 return std::min(InitializableMembers, 1);
478 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000479}
480
Anders Carlsson6cabf312010-01-23 23:23:01 +0000481void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000482 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 QualType T, unsigned &Index,
484 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000485 unsigned &StructuredIndex,
486 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000487 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Steve Narofff8ecff22008-05-01 22:18:59 +0000489 if (T->isArrayType())
490 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000491 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000492 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000493 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000494 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000495 else
496 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000497
Eli Friedmane0f832b2008-05-25 13:49:22 +0000498 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000500 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000501 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000502 hadError = true;
503 return;
504 }
505
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000506 // Build a structured initializer list corresponding to this subobject.
507 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000508 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
509 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000510 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
511 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000512 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000513
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000514 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000515 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000517 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000518 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000519 StructuredSubobjectInitIndex,
520 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000521 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000522 StructuredSubobjectInitList->setType(T);
523
Douglas Gregor5741efb2009-03-01 17:12:46 +0000524 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000525 // range corresponds with the end of the last initializer it used.
526 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000527 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000528 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
529 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
Tanya Lattner5029d562010-03-07 04:17:15 +0000532 // Warn about missing braces.
533 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000534 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
535 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000536 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000538 "{")
539 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000541 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000542 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000543}
544
Anders Carlsson6cabf312010-01-23 23:23:01 +0000545void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000546 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000547 unsigned &Index,
548 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000549 unsigned &StructuredIndex,
550 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000551 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000552 SyntacticToSemantic[IList] = StructuredList;
553 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000555 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000556 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
557 IList->setType(ExprTy);
558 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000559 if (hadError)
560 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000561
Eli Friedman85f54972008-05-25 13:22:35 +0000562 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000563 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000564 if (StructuredIndex == 1 &&
565 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000566 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000567 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000568 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000569 hadError = true;
570 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000571 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000572 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000573 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000574 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000575 // Don't complain for incomplete types, since we'll get an error
576 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000577 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000578 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000579 CurrentObjectType->isArrayType()? 0 :
580 CurrentObjectType->isVectorType()? 1 :
581 CurrentObjectType->isScalarType()? 2 :
582 CurrentObjectType->isUnionType()? 3 :
583 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000584
585 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000586 if (SemaRef.getLangOptions().CPlusPlus) {
587 DK = diag::err_excess_initializers;
588 hadError = true;
589 }
Nate Begeman425038c2009-07-07 21:53:06 +0000590 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
591 DK = diag::err_excess_initializers;
592 hadError = true;
593 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000594
Chris Lattnerb0912a52009-02-24 22:50:46 +0000595 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000596 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000597 }
598 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000599
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000600 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000601 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000602 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000603 << FixItHint::CreateRemoval(IList->getLocStart())
604 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000605}
606
Anders Carlsson6cabf312010-01-23 23:23:01 +0000607void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000608 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000609 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000610 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000611 unsigned &Index,
612 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000613 unsigned &StructuredIndex,
614 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000616 CheckScalarType(Entity, IList, DeclType, Index,
617 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000618 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000620 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000621 } else if (DeclType->isAggregateType()) {
622 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000623 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000624 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000625 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000626 StructuredList, StructuredIndex,
627 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000628 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000629 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000630 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000631 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000633 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000634 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000635 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000636 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000637 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
638 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000639 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000640 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000641 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000642 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000643 } else if (DeclType->isRecordType()) {
644 // C++ [dcl.init]p14:
645 // [...] If the class is an aggregate (8.5.1), and the initializer
646 // is a brace-enclosed list, see 8.5.1.
647 //
648 // Note: 8.5.1 is handled below; here, we diagnose the case where
649 // we have an initializer list and a destination type that is not
650 // an aggregate.
651 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000652 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000653 << DeclType << IList->getSourceRange();
654 hadError = true;
655 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000656 CheckReferenceType(Entity, IList, DeclType, Index,
657 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000658 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000659 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
660 << DeclType;
661 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000662 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000663 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
664 << DeclType;
665 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000666 }
667}
668
Anders Carlsson6cabf312010-01-23 23:23:01 +0000669void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000671 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000672 unsigned &Index,
673 InitListExpr *StructuredList,
674 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000675 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000676 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
677 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000678 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000679 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000680 = getStructuredSubobjectInit(IList, Index, ElemType,
681 StructuredList, StructuredIndex,
682 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000683 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000684 newStructuredList, newStructuredIndex);
685 ++StructuredIndex;
686 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000687 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000688 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000689 return CheckScalarType(Entity, IList, ElemType, Index,
690 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000691 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000692 return CheckReferenceType(Entity, IList, ElemType, Index,
693 StructuredList, StructuredIndex);
694 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000695
John McCall5decec92011-02-21 07:57:55 +0000696 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
697 // arrayType can be incomplete if we're initializing a flexible
698 // array member. There's nothing we can do with the completed
699 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
John McCall5decec92011-02-21 07:57:55 +0000701 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
702 CheckStringInit(Str, ElemType, arrayType, SemaRef);
703 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000704 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000705 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000706 }
John McCall5decec92011-02-21 07:57:55 +0000707
708 // Fall through for subaggregate initialization.
709
710 } else if (SemaRef.getLangOptions().CPlusPlus) {
711 // C++ [dcl.init.aggr]p12:
712 // All implicit type conversions (clause 4) are considered when
Sebastian Redl9c618092011-07-14 19:08:10 +0000713 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000714 // an initializer-list. If the initializer can initialize a
715 // member, the member is initialized. [...]
716
717 // FIXME: Better EqualLoc?
718 InitializationKind Kind =
719 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
720 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
721
722 if (Seq) {
723 ExprResult Result =
724 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
725 if (Result.isInvalid())
726 hadError = true;
727
728 UpdateStructuredListElement(StructuredList, StructuredIndex,
729 Result.takeAs<Expr>());
730 ++Index;
731 return;
732 }
733
734 // Fall through for subaggregate initialization
735 } else {
736 // C99 6.7.8p13:
737 //
738 // The initializer for a structure or union object that has
739 // automatic storage duration shall be either an initializer
740 // list as described below, or a single expression that has
741 // compatible structure or union type. In the latter case, the
742 // initial value of the object, including unnamed members, is
743 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000744 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000745 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000746 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000747 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000748 if (ExprRes.isInvalid())
749 hadError = true;
750 else {
751 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
752 if (ExprRes.isInvalid())
753 hadError = true;
754 }
755 UpdateStructuredListElement(StructuredList, StructuredIndex,
756 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000757 ++Index;
758 return;
759 }
John Wiegley01296292011-04-08 18:41:53 +0000760 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000761 // Fall through for subaggregate initialization
762 }
763
764 // C++ [dcl.init.aggr]p12:
765 //
766 // [...] Otherwise, if the member is itself a non-empty
767 // subaggregate, brace elision is assumed and the initializer is
768 // considered for the initialization of the first member of
769 // the subaggregate.
770 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
771 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
772 StructuredIndex);
773 ++StructuredIndex;
774 } else {
775 // We cannot initialize this element, so let
776 // PerformCopyInitialization produce the appropriate diagnostic.
777 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
778 SemaRef.Owned(expr));
779 hadError = true;
780 ++Index;
781 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000782 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000783}
784
Anders Carlsson6cabf312010-01-23 23:23:01 +0000785void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000786 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000787 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000788 InitListExpr *StructuredList,
789 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000790 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000791 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000792 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000793 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000794 ++Index;
795 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000796 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000797 }
John McCall643169b2010-11-11 00:46:36 +0000798
799 Expr *expr = IList->getInit(Index);
800 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
801 SemaRef.Diag(SubIList->getLocStart(),
802 diag::warn_many_braces_around_scalar_init)
803 << SubIList->getSourceRange();
804
805 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
806 StructuredIndex);
807 return;
808 } else if (isa<DesignatedInitExpr>(expr)) {
809 SemaRef.Diag(expr->getSourceRange().getBegin(),
810 diag::err_designator_for_scalar_init)
811 << DeclType << expr->getSourceRange();
812 hadError = true;
813 ++Index;
814 ++StructuredIndex;
815 return;
816 }
817
818 ExprResult Result =
819 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
820 SemaRef.Owned(expr));
821
822 Expr *ResultExpr = 0;
823
824 if (Result.isInvalid())
825 hadError = true; // types weren't compatible.
826 else {
827 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828
John McCall643169b2010-11-11 00:46:36 +0000829 if (ResultExpr != expr) {
830 // The type was promoted, update initializer list.
831 IList->setInit(Index, ResultExpr);
832 }
833 }
834 if (hadError)
835 ++StructuredIndex;
836 else
837 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
838 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000839}
840
Anders Carlsson6cabf312010-01-23 23:23:01 +0000841void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
842 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000843 unsigned &Index,
844 InitListExpr *StructuredList,
845 unsigned &StructuredIndex) {
846 if (Index < IList->getNumInits()) {
847 Expr *expr = IList->getInit(Index);
848 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000849 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000850 << DeclType << IList->getSourceRange();
851 hadError = true;
852 ++Index;
853 ++StructuredIndex;
854 return;
Mike Stump11289f42009-09-09 15:08:12 +0000855 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000856
John McCalldadc5752010-08-24 06:29:42 +0000857 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000858 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
859 SemaRef.Owned(expr));
860
861 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000863
864 expr = Result.takeAs<Expr>();
865 IList->setInit(Index, expr);
866
Douglas Gregord14247a2009-01-30 22:09:00 +0000867 if (hadError)
868 ++StructuredIndex;
869 else
870 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
871 ++Index;
872 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000873 // FIXME: It would be wonderful if we could point at the actual member. In
874 // general, it would be useful to pass location information down the stack,
875 // so that we know the location (or decl) of the "current object" being
876 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000877 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000878 diag::err_init_reference_member_uninitialized)
879 << DeclType
880 << IList->getSourceRange();
881 hadError = true;
882 ++Index;
883 ++StructuredIndex;
884 return;
885 }
886}
887
Anders Carlsson6cabf312010-01-23 23:23:01 +0000888void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000889 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000890 unsigned &Index,
891 InitListExpr *StructuredList,
892 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000893 if (Index >= IList->getNumInits())
894 return;
Mike Stump11289f42009-09-09 15:08:12 +0000895
John McCall6a16b2f2010-10-30 00:11:39 +0000896 const VectorType *VT = DeclType->getAs<VectorType>();
897 unsigned maxElements = VT->getNumElements();
898 unsigned numEltsInit = 0;
899 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000900
John McCall6a16b2f2010-10-30 00:11:39 +0000901 if (!SemaRef.getLangOptions().OpenCL) {
902 // If the initializing element is a vector, try to copy-initialize
903 // instead of breaking it apart (which is doomed to failure anyway).
904 Expr *Init = IList->getInit(Index);
905 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
906 ExprResult Result =
907 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
908 SemaRef.Owned(Init));
909
910 Expr *ResultExpr = 0;
911 if (Result.isInvalid())
912 hadError = true; // types weren't compatible.
913 else {
914 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000915
John McCall6a16b2f2010-10-30 00:11:39 +0000916 if (ResultExpr != Init) {
917 // The type was promoted, update initializer list.
918 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000919 }
920 }
John McCall6a16b2f2010-10-30 00:11:39 +0000921 if (hadError)
922 ++StructuredIndex;
923 else
924 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
925 ++Index;
926 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
John McCall6a16b2f2010-10-30 00:11:39 +0000929 InitializedEntity ElementEntity =
930 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000931
John McCall6a16b2f2010-10-30 00:11:39 +0000932 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
933 // Don't attempt to go past the end of the init list
934 if (Index >= IList->getNumInits())
935 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936
John McCall6a16b2f2010-10-30 00:11:39 +0000937 ElementEntity.setElementIndex(Index);
938 CheckSubElementType(ElementEntity, IList, elementType, Index,
939 StructuredList, StructuredIndex);
940 }
941 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000942 }
John McCall6a16b2f2010-10-30 00:11:39 +0000943
944 InitializedEntity ElementEntity =
945 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946
John McCall6a16b2f2010-10-30 00:11:39 +0000947 // OpenCL initializers allows vectors to be constructed from vectors.
948 for (unsigned i = 0; i < maxElements; ++i) {
949 // Don't attempt to go past the end of the init list
950 if (Index >= IList->getNumInits())
951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
John McCall6a16b2f2010-10-30 00:11:39 +0000953 ElementEntity.setElementIndex(Index);
954
955 QualType IType = IList->getInit(Index)->getType();
956 if (!IType->isVectorType()) {
957 CheckSubElementType(ElementEntity, IList, elementType, Index,
958 StructuredList, StructuredIndex);
959 ++numEltsInit;
960 } else {
961 QualType VecType;
962 const VectorType *IVT = IType->getAs<VectorType>();
963 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000964
John McCall6a16b2f2010-10-30 00:11:39 +0000965 if (IType->isExtVectorType())
966 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
967 else
968 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000969 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000970 CheckSubElementType(ElementEntity, IList, VecType, Index,
971 StructuredList, StructuredIndex);
972 numEltsInit += numIElts;
973 }
974 }
975
976 // OpenCL requires all elements to be initialized.
977 if (numEltsInit != maxElements)
978 if (SemaRef.getLangOptions().OpenCL)
979 SemaRef.Diag(IList->getSourceRange().getBegin(),
980 diag::err_vector_incorrect_num_initializers)
981 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000982}
983
Anders Carlsson6cabf312010-01-23 23:23:01 +0000984void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000985 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000986 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000987 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000988 unsigned &Index,
989 InitListExpr *StructuredList,
990 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000991 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
992
Steve Narofff8ecff22008-05-01 22:18:59 +0000993 // Check for the special-case of initializing an array with a string.
994 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000995 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000996 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000997 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000998 // We place the string literal directly into the resulting
999 // initializer list. This is the only place where the structure
1000 // of the structured initializer list doesn't match exactly,
1001 // because doing so would involve allocating one character
1002 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001003 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001004 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001005 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001006 return;
1007 }
1008 }
John McCall66884dd2011-02-21 07:22:22 +00001009 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001010 // Check for VLAs; in standard C it would be possible to check this
1011 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1012 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001013 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001014 diag::err_variable_object_no_init)
1015 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001016 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001017 ++Index;
1018 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001019 return;
1020 }
1021
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001022 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001023 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1024 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001025 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001026 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001027 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001028 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001029 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001030 maxElementsKnown = true;
1031 }
1032
John McCall66884dd2011-02-21 07:22:22 +00001033 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001034 while (Index < IList->getNumInits()) {
1035 Expr *Init = IList->getInit(Index);
1036 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001037 // If we're not the subobject that matches up with the '{' for
1038 // the designator, we shouldn't be handling the
1039 // designator. Return immediately.
1040 if (!SubobjectIsDesignatorContext)
1041 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001042
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001043 // Handle this designated initializer. elementIndex will be
1044 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001045 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001046 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001047 StructuredList, StructuredIndex, true,
1048 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001049 hadError = true;
1050 continue;
1051 }
1052
Douglas Gregor033d1252009-01-23 16:54:12 +00001053 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001054 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001055 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001056 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001057 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001058
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001059 // If the array is of incomplete type, keep track of the number of
1060 // elements in the initializer.
1061 if (!maxElementsKnown && elementIndex > maxElements)
1062 maxElements = elementIndex;
1063
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001064 continue;
1065 }
1066
1067 // If we know the maximum number of elements, and we've already
1068 // hit it, stop consuming elements in the initializer list.
1069 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001070 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001071
Anders Carlsson6cabf312010-01-23 23:23:01 +00001072 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001074 Entity);
1075 // Check this element.
1076 CheckSubElementType(ElementEntity, IList, elementType, Index,
1077 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001078 ++elementIndex;
1079
1080 // If the array is of incomplete type, keep track of the number of
1081 // elements in the initializer.
1082 if (!maxElementsKnown && elementIndex > maxElements)
1083 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001084 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001085 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001086 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001087 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001088 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001089 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001090 // Sizing an array implicitly to zero is not allowed by ISO C,
1091 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001092 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001093 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001094 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001095
Mike Stump11289f42009-09-09 15:08:12 +00001096 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001097 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001098 }
1099}
1100
Anders Carlsson6cabf312010-01-23 23:23:01 +00001101void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001102 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001103 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001104 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001105 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001106 unsigned &Index,
1107 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001108 unsigned &StructuredIndex,
1109 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001110 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001111
Eli Friedman23a9e312008-05-19 19:16:24 +00001112 // If the record is invalid, some of it's members are invalid. To avoid
1113 // confusion, we forgo checking the intializer for the entire record.
1114 if (structDecl->isInvalidDecl()) {
1115 hadError = true;
1116 return;
Mike Stump11289f42009-09-09 15:08:12 +00001117 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001118
1119 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1120 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001121 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001122 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001123 Field != FieldEnd; ++Field) {
1124 if (Field->getDeclName()) {
1125 StructuredList->setInitializedFieldInUnion(*Field);
1126 break;
1127 }
1128 }
1129 return;
1130 }
1131
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001132 // If structDecl is a forward declaration, this loop won't do
1133 // anything except look at designated initializers; That's okay,
1134 // because an error should get printed out elsewhere. It might be
1135 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001136 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001137 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001138 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001139 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001140 while (Index < IList->getNumInits()) {
1141 Expr *Init = IList->getInit(Index);
1142
1143 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001144 // If we're not the subobject that matches up with the '{' for
1145 // the designator, we shouldn't be handling the
1146 // designator. Return immediately.
1147 if (!SubobjectIsDesignatorContext)
1148 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001149
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001150 // Handle this designated initializer. Field will be updated to
1151 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001152 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001153 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001154 StructuredList, StructuredIndex,
1155 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001156 hadError = true;
1157
Douglas Gregora9add4e2009-02-12 19:00:39 +00001158 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001159
1160 // Disable check for missing fields when designators are used.
1161 // This matches gcc behaviour.
1162 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001163 continue;
1164 }
1165
1166 if (Field == FieldEnd) {
1167 // We've run out of fields. We're done.
1168 break;
1169 }
1170
Douglas Gregora9add4e2009-02-12 19:00:39 +00001171 // We've already initialized a member of a union. We're done.
1172 if (InitializedSomething && DeclType->isUnionType())
1173 break;
1174
Douglas Gregor91f84212008-12-11 16:49:14 +00001175 // If we've hit the flexible array member at the end, we're done.
1176 if (Field->getType()->isIncompleteArrayType())
1177 break;
1178
Douglas Gregor51695702009-01-29 16:53:55 +00001179 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001181 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001182 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001183 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001184
Douglas Gregora82064c2011-06-29 21:51:31 +00001185 // Make sure we can use this declaration.
1186 if (SemaRef.DiagnoseUseOfDecl(*Field,
1187 IList->getInit(Index)->getLocStart())) {
1188 ++Index;
1189 ++Field;
1190 hadError = true;
1191 continue;
1192 }
1193
Anders Carlsson6cabf312010-01-23 23:23:01 +00001194 InitializedEntity MemberEntity =
1195 InitializedEntity::InitializeMember(*Field, &Entity);
1196 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1197 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001198 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001199
1200 if (DeclType->isUnionType()) {
1201 // Initialize the first field within the union.
1202 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001203 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001204
1205 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001206 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001207
John McCalle40b58e2010-03-11 19:32:38 +00001208 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001210 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1211 // It is possible we have one or more unnamed bitfields remaining.
1212 // Find first (if any) named field and emit warning.
1213 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1214 it != end; ++it) {
1215 if (!it->isUnnamedBitfield()) {
1216 SemaRef.Diag(IList->getSourceRange().getEnd(),
1217 diag::warn_missing_field_initializers) << it->getName();
1218 break;
1219 }
1220 }
1221 }
1222
Mike Stump11289f42009-09-09 15:08:12 +00001223 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001224 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001225 return;
1226
1227 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001228 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001229 (!isa<InitListExpr>(IList->getInit(Index)) ||
1230 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001231 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001232 diag::err_flexible_array_init_nonempty)
1233 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001234 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001235 << *Field;
1236 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001237 ++Index;
1238 return;
1239 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001240 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001241 diag::ext_flexible_array_init)
1242 << IList->getInit(Index)->getSourceRange().getBegin();
1243 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1244 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001245 }
1246
Anders Carlsson6cabf312010-01-23 23:23:01 +00001247 InitializedEntity MemberEntity =
1248 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001249
Anders Carlsson6cabf312010-01-23 23:23:01 +00001250 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001252 StructuredList, StructuredIndex);
1253 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001255 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001256}
Steve Narofff8ecff22008-05-01 22:18:59 +00001257
Douglas Gregord5846a12009-04-15 06:41:24 +00001258/// \brief Expand a field designator that refers to a member of an
1259/// anonymous struct or union into a series of field designators that
1260/// refers to the field within the appropriate subobject.
1261///
Douglas Gregord5846a12009-04-15 06:41:24 +00001262static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001263 DesignatedInitExpr *DIE,
1264 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001265 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001266 typedef DesignatedInitExpr::Designator Designator;
1267
Douglas Gregord5846a12009-04-15 06:41:24 +00001268 // Build the replacement designators.
1269 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001270 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1271 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1272 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001273 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001274 DIE->getDesignator(DesigIdx)->getDotLoc(),
1275 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1276 else
1277 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1278 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001279 assert(isa<FieldDecl>(*PI));
1280 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001281 }
1282
1283 // Expand the current designator into the set of replacement
1284 // designators, so we have a full subobject path down to where the
1285 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001286 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001287 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001288}
Mike Stump11289f42009-09-09 15:08:12 +00001289
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001291/// corresponds to FieldName.
1292static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1293 IdentifierInfo *FieldName) {
1294 assert(AnonField->isAnonymousStructOrUnion());
1295 Decl *NextDecl = AnonField->getNextDeclInContext();
1296 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1297 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1298 return IF;
1299 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001300 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001301 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001302}
1303
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001304/// @brief Check the well-formedness of a C99 designated initializer.
1305///
1306/// Determines whether the designated initializer @p DIE, which
1307/// resides at the given @p Index within the initializer list @p
1308/// IList, is well-formed for a current object of type @p DeclType
1309/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001310/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001311/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001312///
1313/// @param IList The initializer list in which this designated
1314/// initializer occurs.
1315///
Douglas Gregora5324162009-04-15 04:56:10 +00001316/// @param DIE The designated initializer expression.
1317///
1318/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001319///
1320/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1321/// into which the designation in @p DIE should refer.
1322///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001323/// @param NextField If non-NULL and the first designator in @p DIE is
1324/// a field, this will be set to the field declaration corresponding
1325/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001326///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001327/// @param NextElementIndex If non-NULL and the first designator in @p
1328/// DIE is an array designator or GNU array-range designator, this
1329/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001330///
1331/// @param Index Index into @p IList where the designated initializer
1332/// @p DIE occurs.
1333///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001334/// @param StructuredList The initializer list expression that
1335/// describes all of the subobject initializers in the order they'll
1336/// actually be initialized.
1337///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001338/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001339bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001340InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001341 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001342 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001343 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001344 QualType &CurrentObjectType,
1345 RecordDecl::field_iterator *NextField,
1346 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 unsigned &Index,
1348 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001349 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001350 bool FinishSubobjectInit,
1351 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001352 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001353 // Check the actual initialization for the designated object type.
1354 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001355
1356 // Temporarily remove the designator expression from the
1357 // initializer list that the child calls see, so that we don't try
1358 // to re-process the designator.
1359 unsigned OldIndex = Index;
1360 IList->setInit(OldIndex, DIE->getInit());
1361
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001362 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001363 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001364
1365 // Restore the designated initializer expression in the syntactic
1366 // form of the initializer list.
1367 if (IList->getInit(OldIndex) != DIE->getInit())
1368 DIE->setInit(IList->getInit(OldIndex));
1369 IList->setInit(OldIndex, DIE);
1370
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001371 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001372 }
1373
Douglas Gregora5324162009-04-15 04:56:10 +00001374 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001375 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001376 "Need a non-designated initializer list to start from");
1377
Douglas Gregora5324162009-04-15 04:56:10 +00001378 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001379 // Determine the structural initializer list that corresponds to the
1380 // current subobject.
1381 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001382 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001383 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001384 SourceRange(D->getStartLocation(),
1385 DIE->getSourceRange().getEnd()));
1386 assert(StructuredList && "Expected a structured initializer list");
1387
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001388 if (D->isFieldDesignator()) {
1389 // C99 6.7.8p7:
1390 //
1391 // If a designator has the form
1392 //
1393 // . identifier
1394 //
1395 // then the current object (defined below) shall have
1396 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001397 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001398 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001399 if (!RT) {
1400 SourceLocation Loc = D->getDotLoc();
1401 if (Loc.isInvalid())
1402 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001403 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1404 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001405 ++Index;
1406 return true;
1407 }
1408
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001409 // Note: we perform a linear search of the fields here, despite
1410 // the fact that we have a faster lookup method, because we always
1411 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001412 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001413 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001414 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001415 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001416 Field = RT->getDecl()->field_begin(),
1417 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001418 for (; Field != FieldEnd; ++Field) {
1419 if (Field->isUnnamedBitfield())
1420 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001422 // If we find a field representing an anonymous field, look in the
1423 // IndirectFieldDecl that follow for the designated initializer.
1424 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1425 if (IndirectFieldDecl *IF =
1426 FindIndirectFieldDesignator(*Field, FieldName)) {
1427 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1428 D = DIE->getDesignator(DesigIdx);
1429 break;
1430 }
1431 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001432 if (KnownField && KnownField == *Field)
1433 break;
1434 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001435 break;
1436
1437 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001438 }
1439
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001440 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001441 // There was no normal field in the struct with the designated
1442 // name. Perform another lookup for this name, which may find
1443 // something that we can't designate (e.g., a member function),
1444 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001445 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001446 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001447 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001448 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001449 // Name lookup didn't find anything. Determine whether this
1450 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001452 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001453 TypoCorrection Corrected = SemaRef.CorrectTypo(
1454 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1455 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1456 RT->getDecl(), false, Sema::CTC_NoKeywords);
1457 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001458 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001459 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001460 std::string CorrectedStr(
1461 Corrected.getAsString(SemaRef.getLangOptions()));
1462 std::string CorrectedQuotedStr(
1463 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001465 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001466 << FieldName << CurrentObjectType << CorrectedQuotedStr
1467 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001469 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001470 } else {
1471 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1472 << FieldName << CurrentObjectType;
1473 ++Index;
1474 return true;
1475 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001478 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001479 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001480 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001481 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001482 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001483 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001484 ++Index;
1485 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001487
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001488 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001489 // The replacement field comes from typo correction; find it
1490 // in the list of fields.
1491 FieldIndex = 0;
1492 Field = RT->getDecl()->field_begin();
1493 for (; Field != FieldEnd; ++Field) {
1494 if (Field->isUnnamedBitfield())
1495 continue;
1496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001497 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001498 Field->getIdentifier() == ReplacementField->getIdentifier())
1499 break;
1500
1501 ++FieldIndex;
1502 }
1503 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001504 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001505
1506 // All of the fields of a union are located at the same place in
1507 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001508 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001509 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001510 StructuredList->setInitializedFieldInUnion(*Field);
1511 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001512
Douglas Gregora82064c2011-06-29 21:51:31 +00001513 // Make sure we can use this declaration.
1514 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1515 ++Index;
1516 return true;
1517 }
1518
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001519 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001520 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001521
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001522 // Make sure that our non-designated initializer list has space
1523 // for a subobject corresponding to this field.
1524 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001525 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001526
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001527 // This designator names a flexible array member.
1528 if (Field->getType()->isIncompleteArrayType()) {
1529 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001530 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001531 // We can't designate an object within the flexible array
1532 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001533 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001534 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001535 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001536 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001537 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001538 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001539 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001540 << *Field;
1541 Invalid = true;
1542 }
1543
Chris Lattner001b29c2010-10-10 17:49:49 +00001544 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1545 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001546 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001547 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001548 diag::err_flexible_array_init_needs_braces)
1549 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001550 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001551 << *Field;
1552 Invalid = true;
1553 }
1554
1555 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001556 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001557 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001558 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001559 diag::err_flexible_array_init_nonempty)
1560 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001561 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001562 << *Field;
1563 Invalid = true;
1564 }
1565
1566 if (Invalid) {
1567 ++Index;
1568 return true;
1569 }
1570
1571 // Initialize the array.
1572 bool prevHadError = hadError;
1573 unsigned newStructuredIndex = FieldIndex;
1574 unsigned OldIndex = Index;
1575 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001576
1577 InitializedEntity MemberEntity =
1578 InitializedEntity::InitializeMember(*Field, &Entity);
1579 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001580 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001581
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001582 IList->setInit(OldIndex, DIE);
1583 if (hadError && !prevHadError) {
1584 ++Field;
1585 ++FieldIndex;
1586 if (NextField)
1587 *NextField = Field;
1588 StructuredIndex = FieldIndex;
1589 return true;
1590 }
1591 } else {
1592 // Recurse to check later designated subobjects.
1593 QualType FieldType = (*Field)->getType();
1594 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001596 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001597 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001598 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1599 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001600 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001601 true, false))
1602 return true;
1603 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001604
1605 // Find the position of the next field to be initialized in this
1606 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001607 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001608 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609
1610 // If this the first designator, our caller will continue checking
1611 // the rest of this struct/class/union subobject.
1612 if (IsFirstDesignator) {
1613 if (NextField)
1614 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001615 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001616 return false;
1617 }
1618
Douglas Gregor17bd0942009-01-28 23:36:17 +00001619 if (!FinishSubobjectInit)
1620 return false;
1621
Douglas Gregord5846a12009-04-15 06:41:24 +00001622 // We've already initialized something in the union; we're done.
1623 if (RT->getDecl()->isUnion())
1624 return hadError;
1625
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001626 // Check the remaining fields within this class/struct/union subobject.
1627 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001628
Anders Carlsson6cabf312010-01-23 23:23:01 +00001629 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001630 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001631 return hadError && !prevHadError;
1632 }
1633
1634 // C99 6.7.8p6:
1635 //
1636 // If a designator has the form
1637 //
1638 // [ constant-expression ]
1639 //
1640 // then the current object (defined below) shall have array
1641 // type and the expression shall be an integer constant
1642 // expression. If the array is of unknown size, any
1643 // nonnegative value is valid.
1644 //
1645 // Additionally, cope with the GNU extension that permits
1646 // designators of the form
1647 //
1648 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001649 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001650 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001651 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 << CurrentObjectType;
1653 ++Index;
1654 return true;
1655 }
1656
1657 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001658 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1659 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001660 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001661 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001662 DesignatedEndIndex = DesignatedStartIndex;
1663 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001665
Mike Stump11289f42009-09-09 15:08:12 +00001666 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001667 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001668 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001669 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001670 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001671
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001672 // Codegen can't handle evaluating array range designators that have side
1673 // effects, because we replicate the AST value for each initialized element.
1674 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1675 // elements with something that has a side effect, so codegen can emit an
1676 // "error unsupported" error instead of miscompiling the app.
1677 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1678 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001679 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001680 }
1681
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001682 if (isa<ConstantArrayType>(AT)) {
1683 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001684 DesignatedStartIndex
1685 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001686 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001687 DesignatedEndIndex
1688 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001689 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1690 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001691 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001692 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001693 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001694 << IndexExpr->getSourceRange();
1695 ++Index;
1696 return true;
1697 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001698 } else {
1699 // Make sure the bit-widths and signedness match.
1700 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001701 DesignatedEndIndex
1702 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001703 else if (DesignatedStartIndex.getBitWidth() <
1704 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001705 DesignatedStartIndex
1706 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001707 DesignatedStartIndex.setIsUnsigned(true);
1708 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 // Make sure that our non-designated initializer list has space
1712 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001713 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001714 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001715 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001716
Douglas Gregor17bd0942009-01-28 23:36:17 +00001717 // Repeatedly perform subobject initializations in the range
1718 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001719
Douglas Gregor17bd0942009-01-28 23:36:17 +00001720 // Move to the next designator
1721 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1722 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001724 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001725 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001726
Douglas Gregor17bd0942009-01-28 23:36:17 +00001727 while (DesignatedStartIndex <= DesignatedEndIndex) {
1728 // Recurse to check later designated subobjects.
1729 QualType ElementType = AT->getElementType();
1730 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001732 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1734 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001735 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001736 (DesignatedStartIndex == DesignatedEndIndex),
1737 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001738 return true;
1739
1740 // Move to the next index in the array that we'll be initializing.
1741 ++DesignatedStartIndex;
1742 ElementIndex = DesignatedStartIndex.getZExtValue();
1743 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001744
1745 // If this the first designator, our caller will continue checking
1746 // the rest of this array subobject.
1747 if (IsFirstDesignator) {
1748 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001749 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001750 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001751 return false;
1752 }
Mike Stump11289f42009-09-09 15:08:12 +00001753
Douglas Gregor17bd0942009-01-28 23:36:17 +00001754 if (!FinishSubobjectInit)
1755 return false;
1756
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001757 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001758 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001760 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001761 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001762 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001763}
1764
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765// Get the structured initializer list for a subobject of type
1766// @p CurrentObjectType.
1767InitListExpr *
1768InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1769 QualType CurrentObjectType,
1770 InitListExpr *StructuredList,
1771 unsigned StructuredIndex,
1772 SourceRange InitRange) {
1773 Expr *ExistingInit = 0;
1774 if (!StructuredList)
1775 ExistingInit = SyntacticToSemantic[IList];
1776 else if (StructuredIndex < StructuredList->getNumInits())
1777 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001779 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1780 return Result;
1781
1782 if (ExistingInit) {
1783 // We are creating an initializer list that initializes the
1784 // subobjects of the current object, but there was already an
1785 // initialization that completely initialized the current
1786 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001787 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001788 // struct X { int a, b; };
1789 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001790 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001791 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1792 // designated initializer re-initializes the whole
1793 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001794 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001795 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001796 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001797 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001798 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001799 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001800 << ExistingInit->getSourceRange();
1801 }
1802
Mike Stump11289f42009-09-09 15:08:12 +00001803 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001804 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1805 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001806 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001807
Douglas Gregora8a089b2010-07-13 18:40:04 +00001808 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001809
Douglas Gregor6d00c992009-03-20 23:58:33 +00001810 // Pre-allocate storage for the structured initializer list.
1811 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001812 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001813 bool GotNumInits = false;
1814 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001815 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001816 GotNumInits = true;
1817 } else if (Index < IList->getNumInits()) {
1818 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001819 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001820 GotNumInits = true;
1821 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001822 }
1823
Mike Stump11289f42009-09-09 15:08:12 +00001824 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001825 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1826 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1827 NumElements = CAType->getSize().getZExtValue();
1828 // Simple heuristic so that we don't allocate a very large
1829 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001830 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001831 NumElements = 0;
1832 }
John McCall9dd450b2009-09-21 23:43:11 +00001833 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001834 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001835 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001836 RecordDecl *RDecl = RType->getDecl();
1837 if (RDecl->isUnion())
1838 NumElements = 1;
1839 else
Mike Stump11289f42009-09-09 15:08:12 +00001840 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001841 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001842 }
1843
Douglas Gregor221c9a52009-03-21 18:13:52 +00001844 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001845 NumElements = IList->getNumInits();
1846
Ted Kremenekac034612010-04-13 23:39:13 +00001847 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001848
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001849 // Link this new initializer list into the structured initializer
1850 // lists.
1851 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001852 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001853 else {
1854 Result->setSyntacticForm(IList);
1855 SyntacticToSemantic[IList] = Result;
1856 }
1857
1858 return Result;
1859}
1860
1861/// Update the initializer at index @p StructuredIndex within the
1862/// structured initializer list to the value @p expr.
1863void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1864 unsigned &StructuredIndex,
1865 Expr *expr) {
1866 // No structured initializer list to update
1867 if (!StructuredList)
1868 return;
1869
Ted Kremenekac034612010-04-13 23:39:13 +00001870 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1871 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001872 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001873 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 diag::warn_initializer_overrides)
1875 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001876 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001877 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001878 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001879 << PrevInit->getSourceRange();
1880 }
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001882 ++StructuredIndex;
1883}
1884
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001885/// Check that the given Index expression is a valid array designator
1886/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001887/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001888/// and produces a reasonable diagnostic if there is a
1889/// failure. Returns true if there was an error, false otherwise. If
1890/// everything went okay, Value will receive the value of the constant
1891/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001892static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001893CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001894 SourceLocation Loc = Index->getSourceRange().getBegin();
1895
1896 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001897 if (S.VerifyIntegerConstantExpression(Index, &Value))
1898 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001899
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001900 if (Value.isSigned() && Value.isNegative())
1901 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001902 << Value.toString(10) << Index->getSourceRange();
1903
Douglas Gregor51650d32009-01-23 21:04:18 +00001904 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 return false;
1906}
1907
John McCalldadc5752010-08-24 06:29:42 +00001908ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001909 SourceLocation Loc,
1910 bool GNUSyntax,
1911 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001912 typedef DesignatedInitExpr::Designator ASTDesignator;
1913
1914 bool Invalid = false;
1915 llvm::SmallVector<ASTDesignator, 32> Designators;
1916 llvm::SmallVector<Expr *, 32> InitExpressions;
1917
1918 // Build designators and check array designator expressions.
1919 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1920 const Designator &D = Desig.getDesignator(Idx);
1921 switch (D.getKind()) {
1922 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001923 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001924 D.getFieldLoc()));
1925 break;
1926
1927 case Designator::ArrayDesignator: {
1928 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1929 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001930 if (!Index->isTypeDependent() &&
1931 !Index->isValueDependent() &&
1932 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001933 Invalid = true;
1934 else {
1935 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001936 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001937 D.getRBracketLoc()));
1938 InitExpressions.push_back(Index);
1939 }
1940 break;
1941 }
1942
1943 case Designator::ArrayRangeDesignator: {
1944 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1945 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1946 llvm::APSInt StartValue;
1947 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001948 bool StartDependent = StartIndex->isTypeDependent() ||
1949 StartIndex->isValueDependent();
1950 bool EndDependent = EndIndex->isTypeDependent() ||
1951 EndIndex->isValueDependent();
1952 if ((!StartDependent &&
1953 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1954 (!EndDependent &&
1955 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001956 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001957 else {
1958 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001959 if (StartDependent || EndDependent) {
1960 // Nothing to compute.
1961 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001962 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001963 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001964 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001965
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001966 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001967 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001968 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001969 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1970 Invalid = true;
1971 } else {
1972 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001973 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001974 D.getEllipsisLoc(),
1975 D.getRBracketLoc()));
1976 InitExpressions.push_back(StartIndex);
1977 InitExpressions.push_back(EndIndex);
1978 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001979 }
1980 break;
1981 }
1982 }
1983 }
1984
1985 if (Invalid || Init.isInvalid())
1986 return ExprError();
1987
1988 // Clear out the expressions within the designation.
1989 Desig.ClearExprs(*this);
1990
1991 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001992 = DesignatedInitExpr::Create(Context,
1993 Designators.data(), Designators.size(),
1994 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001995 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996
Douglas Gregorc124e592011-01-16 16:13:16 +00001997 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00001998 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
1999 << DIE->getSourceRange();
2000 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002001 Diag(DIE->getLocStart(), diag::ext_designated_init)
2002 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002004 return Owned(DIE);
2005}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002006
Douglas Gregor723796a2009-12-16 06:35:08 +00002007bool Sema::CheckInitList(const InitializedEntity &Entity,
2008 InitListExpr *&InitList, QualType &DeclType) {
2009 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00002010 if (!CheckInitList.HadError())
2011 InitList = CheckInitList.getFullyStructuredList();
2012
2013 return CheckInitList.HadError();
2014}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00002015
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002016//===----------------------------------------------------------------------===//
2017// Initialization entity
2018//===----------------------------------------------------------------------===//
2019
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002021 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002023{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002024 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2025 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002026 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002027 } else {
2028 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002029 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002030 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002031}
2032
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002034 CXXBaseSpecifier *Base,
2035 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002036{
2037 InitializedEntity Result;
2038 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002039 Result.Base = reinterpret_cast<uintptr_t>(Base);
2040 if (IsInheritedVirtualBase)
2041 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Douglas Gregor1b303932009-12-22 15:35:07 +00002043 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002044 return Result;
2045}
2046
Douglas Gregor85dabae2009-12-16 01:38:02 +00002047DeclarationName InitializedEntity::getName() const {
2048 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002049 case EK_Parameter: {
2050 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2051 return (D ? D->getDeclName() : DeclarationName());
2052 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002053
2054 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002055 case EK_Member:
2056 return VariableOrMember->getDeclName();
2057
2058 case EK_Result:
2059 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002060 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002061 case EK_Temporary:
2062 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002063 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002064 case EK_ArrayElement:
2065 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002066 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002067 return DeclarationName();
2068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Douglas Gregor85dabae2009-12-16 01:38:02 +00002070 // Silence GCC warning
2071 return DeclarationName();
2072}
2073
Douglas Gregora4b592a2009-12-19 03:01:41 +00002074DeclaratorDecl *InitializedEntity::getDecl() const {
2075 switch (getKind()) {
2076 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002077 case EK_Member:
2078 return VariableOrMember;
2079
John McCall31168b02011-06-15 23:02:42 +00002080 case EK_Parameter:
2081 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2082
Douglas Gregora4b592a2009-12-19 03:01:41 +00002083 case EK_Result:
2084 case EK_Exception:
2085 case EK_New:
2086 case EK_Temporary:
2087 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002088 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002089 case EK_ArrayElement:
2090 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002091 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002092 return 0;
2093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Douglas Gregora4b592a2009-12-19 03:01:41 +00002095 // Silence GCC warning
2096 return 0;
2097}
2098
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002099bool InitializedEntity::allowsNRVO() const {
2100 switch (getKind()) {
2101 case EK_Result:
2102 case EK_Exception:
2103 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002105 case EK_Variable:
2106 case EK_Parameter:
2107 case EK_Member:
2108 case EK_New:
2109 case EK_Temporary:
2110 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002111 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002112 case EK_ArrayElement:
2113 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002114 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002115 break;
2116 }
2117
2118 return false;
2119}
2120
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002121//===----------------------------------------------------------------------===//
2122// Initialization sequence
2123//===----------------------------------------------------------------------===//
2124
2125void InitializationSequence::Step::Destroy() {
2126 switch (Kind) {
2127 case SK_ResolveAddressOfOverloadedFunction:
2128 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002129 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002130 case SK_CastDerivedToBaseLValue:
2131 case SK_BindReference:
2132 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002133 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002134 case SK_UserConversion:
2135 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002136 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002137 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002138 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002139 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002140 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002141 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002142 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002143 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002144 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002145 case SK_PassByIndirectCopyRestore:
2146 case SK_PassByIndirectRestore:
2147 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002148 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002150 case SK_ConversionSequence:
2151 delete ICS;
2152 }
2153}
2154
Douglas Gregor838fcc32010-03-26 20:14:36 +00002155bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002156 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002157}
2158
2159bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002160 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002161 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Douglas Gregor838fcc32010-03-26 20:14:36 +00002163 switch (getFailureKind()) {
2164 case FK_TooManyInitsForReference:
2165 case FK_ArrayNeedsInitList:
2166 case FK_ArrayNeedsInitListOrStringLiteral:
2167 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2168 case FK_NonConstLValueReferenceBindingToTemporary:
2169 case FK_NonConstLValueReferenceBindingToUnrelated:
2170 case FK_RValueReferenceBindingToLValue:
2171 case FK_ReferenceInitDropsQualifiers:
2172 case FK_ReferenceInitFailed:
2173 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002174 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002175 case FK_TooManyInitsForScalar:
2176 case FK_ReferenceBindingToInitList:
2177 case FK_InitListBadDestinationType:
2178 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002179 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002180 case FK_ArrayTypeMismatch:
2181 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002182 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183
Douglas Gregor838fcc32010-03-26 20:14:36 +00002184 case FK_ReferenceInitOverloadFailed:
2185 case FK_UserConversionOverloadFailed:
2186 case FK_ConstructorOverloadFailed:
2187 return FailedOverloadResult == OR_Ambiguous;
2188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189
Douglas Gregor838fcc32010-03-26 20:14:36 +00002190 return false;
2191}
2192
Douglas Gregorb33eed02010-04-16 22:09:46 +00002193bool InitializationSequence::isConstructorInitialization() const {
2194 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2195}
2196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002197void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002198 FunctionDecl *Function,
2199 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002200 Step S;
2201 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2202 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002203 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002204 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002205 Steps.push_back(S);
2206}
2207
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002209 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002210 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002211 switch (VK) {
2212 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2213 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2214 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002215 default: llvm_unreachable("No such category");
2216 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002217 S.Type = BaseType;
2218 Steps.push_back(S);
2219}
2220
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002221void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002222 bool BindingTemporary) {
2223 Step S;
2224 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2225 S.Type = T;
2226 Steps.push_back(S);
2227}
2228
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002229void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2230 Step S;
2231 S.Kind = SK_ExtraneousCopyToTemporary;
2232 S.Type = T;
2233 Steps.push_back(S);
2234}
2235
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002236void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002237 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002238 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002239 Step S;
2240 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002241 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002242 S.Function.Function = Function;
2243 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002244 Steps.push_back(S);
2245}
2246
2247void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002248 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002249 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002250 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002251 switch (VK) {
2252 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002253 S.Kind = SK_QualificationConversionRValue;
2254 break;
John McCall2536c6d2010-08-25 10:28:54 +00002255 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002256 S.Kind = SK_QualificationConversionXValue;
2257 break;
John McCall2536c6d2010-08-25 10:28:54 +00002258 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002259 S.Kind = SK_QualificationConversionLValue;
2260 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002261 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002262 S.Type = Ty;
2263 Steps.push_back(S);
2264}
2265
2266void InitializationSequence::AddConversionSequenceStep(
2267 const ImplicitConversionSequence &ICS,
2268 QualType T) {
2269 Step S;
2270 S.Kind = SK_ConversionSequence;
2271 S.Type = T;
2272 S.ICS = new ImplicitConversionSequence(ICS);
2273 Steps.push_back(S);
2274}
2275
Douglas Gregor51e77d52009-12-10 17:56:55 +00002276void InitializationSequence::AddListInitializationStep(QualType T) {
2277 Step S;
2278 S.Kind = SK_ListInitialization;
2279 S.Type = T;
2280 Steps.push_back(S);
2281}
2282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002284InitializationSequence::AddConstructorInitializationStep(
2285 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002286 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002287 QualType T) {
2288 Step S;
2289 S.Kind = SK_ConstructorInitialization;
2290 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002291 S.Function.Function = Constructor;
2292 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002293 Steps.push_back(S);
2294}
2295
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002296void InitializationSequence::AddZeroInitializationStep(QualType T) {
2297 Step S;
2298 S.Kind = SK_ZeroInitialization;
2299 S.Type = T;
2300 Steps.push_back(S);
2301}
2302
Douglas Gregore1314a62009-12-18 05:02:21 +00002303void InitializationSequence::AddCAssignmentStep(QualType T) {
2304 Step S;
2305 S.Kind = SK_CAssignment;
2306 S.Type = T;
2307 Steps.push_back(S);
2308}
2309
Eli Friedman78275202009-12-19 08:11:05 +00002310void InitializationSequence::AddStringInitStep(QualType T) {
2311 Step S;
2312 S.Kind = SK_StringInit;
2313 S.Type = T;
2314 Steps.push_back(S);
2315}
2316
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002317void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2318 Step S;
2319 S.Kind = SK_ObjCObjectConversion;
2320 S.Type = T;
2321 Steps.push_back(S);
2322}
2323
Douglas Gregore2f943b2011-02-22 18:29:51 +00002324void InitializationSequence::AddArrayInitStep(QualType T) {
2325 Step S;
2326 S.Kind = SK_ArrayInit;
2327 S.Type = T;
2328 Steps.push_back(S);
2329}
2330
John McCall31168b02011-06-15 23:02:42 +00002331void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2332 bool shouldCopy) {
2333 Step s;
2334 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2335 : SK_PassByIndirectRestore);
2336 s.Type = type;
2337 Steps.push_back(s);
2338}
2339
2340void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2341 Step S;
2342 S.Kind = SK_ProduceObjCObject;
2343 S.Type = T;
2344 Steps.push_back(S);
2345}
2346
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002348 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002349 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002350 this->Failure = Failure;
2351 this->FailedOverloadResult = Result;
2352}
2353
2354//===----------------------------------------------------------------------===//
2355// Attempt initialization
2356//===----------------------------------------------------------------------===//
2357
John McCall31168b02011-06-15 23:02:42 +00002358static void MaybeProduceObjCObject(Sema &S,
2359 InitializationSequence &Sequence,
2360 const InitializedEntity &Entity) {
2361 if (!S.getLangOptions().ObjCAutoRefCount) return;
2362
2363 /// When initializing a parameter, produce the value if it's marked
2364 /// __attribute__((ns_consumed)).
2365 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2366 if (!Entity.isParameterConsumed())
2367 return;
2368
2369 assert(Entity.getType()->isObjCRetainableType() &&
2370 "consuming an object of unretainable type?");
2371 Sequence.AddProduceObjCObjectStep(Entity.getType());
2372
2373 /// When initializing a return value, if the return type is a
2374 /// retainable type, then returns need to immediately retain the
2375 /// object. If an autorelease is required, it will be done at the
2376 /// last instant.
2377 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2378 if (!Entity.getType()->isObjCRetainableType())
2379 return;
2380
2381 Sequence.AddProduceObjCObjectStep(Entity.getType());
2382 }
2383}
2384
Sebastian Redl9c618092011-07-14 19:08:10 +00002385static void SelectInitialization(Sema &S, const InitializedEntity &Entity,
2386 const InitializationKind &Kind,
2387 Expr **Args, unsigned NumArgs,
2388 InitializationSequence &Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002389
2390/// \brief Try a reference initialization that involves calling a conversion
2391/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002392static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2393 const InitializedEntity &Entity,
2394 const InitializationKind &Kind,
2395 Expr *Initializer,
2396 bool AllowRValues,
2397 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002398 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2400 QualType T1 = cv1T1.getUnqualifiedType();
2401 QualType cv2T2 = Initializer->getType();
2402 QualType T2 = cv2T2.getUnqualifiedType();
2403
2404 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002405 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002406 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002407 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002408 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002409 ObjCConversion,
2410 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002411 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002412 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002413 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002414 (void)ObjCLifetimeConversion;
2415
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002416 // Build the candidate set directly in the initialization sequence
2417 // structure, so that it will persist if we fail.
2418 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2419 CandidateSet.clear();
2420
2421 // Determine whether we are allowed to call explicit constructors or
2422 // explicit conversion operators.
2423 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002424
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002425 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002426 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2427 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002428 // The type we're converting to is a class type. Enumerate its constructors
2429 // to see if there is a suitable conversion.
2430 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002433 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002434 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002435 NamedDecl *D = *Con;
2436 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2437
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002438 // Find the constructor (which may be a template).
2439 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002440 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002441 if (ConstructorTmpl)
2442 Constructor = cast<CXXConstructorDecl>(
2443 ConstructorTmpl->getTemplatedDecl());
2444 else
John McCalla0296f72010-03-19 07:35:19 +00002445 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002446
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002447 if (!Constructor->isInvalidDecl() &&
2448 Constructor->isConvertingConstructor(AllowExplicit)) {
2449 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002450 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002451 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002452 &Initializer, 1, CandidateSet,
2453 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002454 else
John McCalla0296f72010-03-19 07:35:19 +00002455 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002456 &Initializer, 1, CandidateSet,
2457 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 }
John McCall3696dcb2010-08-17 07:23:57 +00002461 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2462 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463
Douglas Gregor496e8b342010-05-07 19:42:26 +00002464 const RecordType *T2RecordType = 0;
2465 if ((T2RecordType = T2->getAs<RecordType>()) &&
2466 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002467 // The type we're converting from is a class type, enumerate its conversion
2468 // functions.
2469 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2470
John McCallad371252010-01-20 00:46:10 +00002471 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002472 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002473 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2474 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002475 NamedDecl *D = *I;
2476 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2477 if (isa<UsingShadowDecl>(D))
2478 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002479
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002480 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2481 CXXConversionDecl *Conv;
2482 if (ConvTemplate)
2483 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2484 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002485 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 // If the conversion function doesn't return a reference type,
2488 // it can't be considered for this conversion unless we're allowed to
2489 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002490 // FIXME: Do we need to make sure that we only consider conversion
2491 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002492 // break recursion.
2493 if ((AllowExplicit || !Conv->isExplicit()) &&
2494 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2495 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002496 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002497 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002498 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 else
John McCalla0296f72010-03-19 07:35:19 +00002500 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002501 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002502 }
2503 }
2504 }
John McCall3696dcb2010-08-17 07:23:57 +00002505 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2506 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002508 SourceLocation DeclLoc = Initializer->getLocStart();
2509
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002510 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002511 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002513 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002514 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002515
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002516 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002517
Chandler Carruth30141632011-02-25 19:41:05 +00002518 // This is the overload that will actually be used for the initialization, so
2519 // mark it as used.
2520 S.MarkDeclarationReferenced(DeclLoc, Function);
2521
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002522 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002523 if (isa<CXXConversionDecl>(Function))
2524 T2 = Function->getResultType();
2525 else
2526 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002527
2528 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002529 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002530 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002531
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002533 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002534 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002535 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002536 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002537 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002538 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002540 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002541 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002542 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002543 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002545 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002546 NewDerivedToBase, NewObjCConversion,
2547 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002548 if (NewRefRelationship == Sema::Ref_Incompatible) {
2549 // If the type we've converted to is not reference-related to the
2550 // type we're looking for, then there is another conversion step
2551 // we need to perform to produce a temporary of the right type
2552 // that we'll be binding to.
2553 ImplicitConversionSequence ICS;
2554 ICS.setStandard();
2555 ICS.Standard = Best->FinalConversion;
2556 T2 = ICS.Standard.getToType(2);
2557 Sequence.AddConversionSequenceStep(ICS, T2);
2558 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559 Sequence.AddDerivedToBaseCastStep(
2560 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002561 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002562 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002563 else if (NewObjCConversion)
2564 Sequence.AddObjCObjectConversionStep(
2565 S.Context.getQualifiedType(T1,
2566 T2.getNonReferenceType().getQualifiers()));
2567
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002568 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002569 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002571 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2572 return OR_Success;
2573}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574
2575/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2576static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002577 const InitializedEntity &Entity,
2578 const InitializationKind &Kind,
2579 Expr *Initializer,
2580 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002581 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002582 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002583 Qualifiers T1Quals;
2584 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002585 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002586 Qualifiers T2Quals;
2587 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002589
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002590 // If the initializer is the address of an overloaded function, try
2591 // to resolve the overloaded function. If all goes well, T2 is the
2592 // type of the resulting function.
2593 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002594 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002596 T1,
2597 false,
2598 Found)) {
2599 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2600 cv2T2 = Fn->getType();
2601 T2 = cv2T2.getUnqualifiedType();
2602 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2604 return;
2605 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002606 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002607
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002608 // Compute some basic properties of the types and the initializer.
2609 bool isLValueRef = DestType->isLValueReferenceType();
2610 bool isRValueRef = !isLValueRef;
2611 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002612 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002613 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002614 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002615 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002616 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002617 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002618
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002619 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002621 // "cv2 T2" as follows:
2622 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002623 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002624 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002625 // Note the analogous bullet points for rvlaue refs to functions. Because
2626 // there are no function rvalues in C++, rvalue refs to functions are treated
2627 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002628 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002629 bool T1Function = T1->isFunctionType();
2630 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002631 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002632 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002633 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002634 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002635 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002636 // reference-compatible with "cv2 T2," or
2637 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002639 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002640 // can occur. However, we do pay attention to whether it is a bit-field
2641 // to decide whether we're actually binding to a temporary created from
2642 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002643 if (DerivedToBase)
2644 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002645 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002646 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002647 else if (ObjCConversion)
2648 Sequence.AddObjCObjectConversionStep(
2649 S.Context.getQualifiedType(T1, T2Quals));
2650
Chandler Carruth04bdce62010-01-12 20:32:25 +00002651 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002652 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002653 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002654 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002655 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002656 return;
2657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658
2659 // - has a class type (i.e., T2 is a class type), where T1 is not
2660 // reference-related to T2, and can be implicitly converted to an
2661 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2662 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002663 // applicable conversion functions (13.3.1.6) and choosing the best
2664 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002665 // If we have an rvalue ref to function type here, the rhs must be
2666 // an rvalue.
2667 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2668 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002671 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002672 Sequence);
2673 if (ConvOvlResult == OR_Success)
2674 return;
John McCall0d1da222010-01-12 00:44:57 +00002675 if (ConvOvlResult != OR_No_Viable_Function) {
2676 Sequence.SetOverloadFailure(
2677 InitializationSequence::FK_ReferenceInitOverloadFailed,
2678 ConvOvlResult);
2679 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002680 }
2681 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002684 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002685 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002686 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002687 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2688 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2689 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002690 Sequence.SetOverloadFailure(
2691 InitializationSequence::FK_ReferenceInitOverloadFailed,
2692 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002693 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002694 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002695 ? (RefRelationship == Sema::Ref_Related
2696 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2697 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2698 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002699
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002700 return;
2701 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002702
Douglas Gregor92e460e2011-01-20 16:44:54 +00002703 // - If the initializer expression
2704 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2705 // "cv1 T1" is reference-compatible with "cv2 T2"
2706 // Note: functions are handled below.
2707 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002708 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002710 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002711 (InitCategory.isXValue() ||
2712 (InitCategory.isPRValue() && T2->isRecordType()) ||
2713 (InitCategory.isPRValue() && T2->isArrayType()))) {
2714 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2715 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002716 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2717 // compiler the freedom to perform a copy here or bind to the
2718 // object, while C++0x requires that we bind directly to the
2719 // object. Hence, we always bind to the object without making an
2720 // extra copy. However, in C++03 requires that we check for the
2721 // presence of a suitable copy constructor:
2722 //
2723 // The constructor that would be used to make the copy shall
2724 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002725 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002726 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002728
Douglas Gregor92e460e2011-01-20 16:44:54 +00002729 if (DerivedToBase)
2730 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2731 ValueKind);
2732 else if (ObjCConversion)
2733 Sequence.AddObjCObjectConversionStep(
2734 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002735
Douglas Gregor92e460e2011-01-20 16:44:54 +00002736 if (T1Quals != T2Quals)
2737 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002739 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002740 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002742
2743 // - has a class type (i.e., T2 is a class type), where T1 is not
2744 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002745 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2746 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002747 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002748 if (RefRelationship == Sema::Ref_Incompatible) {
2749 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2750 Kind, Initializer,
2751 /*AllowRValues=*/true,
2752 Sequence);
2753 if (ConvOvlResult)
2754 Sequence.SetOverloadFailure(
2755 InitializationSequence::FK_ReferenceInitOverloadFailed,
2756 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 return;
2759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002761 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2762 return;
2763 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002764
2765 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002766 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002768 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002770 // Determine whether we are allowed to call explicit constructors or
2771 // explicit conversion operators.
2772 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002773
2774 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2775
John McCall31168b02011-06-15 23:02:42 +00002776 ImplicitConversionSequence ICS
2777 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00002778 /*SuppressUserConversions*/ false,
2779 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002780 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00002781 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2782 /*AllowObjCWritebackConversion=*/false);
2783
2784 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785 // FIXME: Use the conversion function set stored in ICS to turn
2786 // this into an overloading ambiguity diagnostic. However, we need
2787 // to keep that set as an OverloadCandidateSet rather than as some
2788 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002789 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2790 Sequence.SetOverloadFailure(
2791 InitializationSequence::FK_ReferenceInitOverloadFailed,
2792 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002793 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2794 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002795 else
2796 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002797 return;
John McCall31168b02011-06-15 23:02:42 +00002798 } else {
2799 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002800 }
2801
2802 // [...] If T1 is reference-related to T2, cv1 must be the
2803 // same cv-qualification as, or greater cv-qualification
2804 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002805 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2806 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002807 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002808 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002809 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2810 return;
2811 }
2812
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002814 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002815 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002816 InitCategory.isLValue()) {
2817 Sequence.SetFailed(
2818 InitializationSequence::FK_RValueReferenceBindingToLValue);
2819 return;
2820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002822 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2823 return;
2824}
2825
2826/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827/// (C++ [dcl.init.string], C99 6.7.8).
2828static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002829 const InitializedEntity &Entity,
2830 const InitializationKind &Kind,
2831 Expr *Initializer,
2832 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002833 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002834}
2835
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002836/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2837/// enumerates the constructors of the initialized entity and performs overload
2838/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002839static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002840 const InitializedEntity &Entity,
2841 const InitializationKind &Kind,
2842 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002843 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002844 InitializationSequence &Sequence) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002845 // Build the candidate set directly in the initialization sequence
2846 // structure, so that it will persist if we fail.
2847 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2848 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002849
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002850 // Determine whether we are allowed to call explicit constructors or
2851 // explicit conversion operators.
2852 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2853 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002854 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002855
2856 // The type we're constructing needs to be complete.
2857 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002858 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002859 return;
2860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002861
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002862 // The type we're converting to is a class type. Enumerate its constructors
2863 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002864 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002866 CXXRecordDecl *DestRecordDecl
2867 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002869 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002870 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002871 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002872 NamedDecl *D = *Con;
2873 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002874 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002876 // Find the constructor (which may be a template).
2877 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002878 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002879 if (ConstructorTmpl)
2880 Constructor = cast<CXXConstructorDecl>(
2881 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002882 else {
John McCalla0296f72010-03-19 07:35:19 +00002883 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002884
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002886 // suppress user-defined conversions on the arguments.
2887 // FIXME: Move constructors?
2888 if (Kind.getKind() == InitializationKind::IK_Copy &&
2889 Constructor->isCopyConstructor())
2890 SuppressUserConversions = true;
2891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002892
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002893 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002894 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002895 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002896 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002897 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002898 Args, NumArgs, CandidateSet,
2899 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002900 else
John McCalla0296f72010-03-19 07:35:19 +00002901 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002902 Args, NumArgs, CandidateSet,
2903 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905 }
2906
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002907 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908
2909 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002910 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002912 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002913 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002915 Result);
2916 return;
2917 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002918
2919 // C++0x [dcl.init]p6:
2920 // If a program calls for the default initialization of an object
2921 // of a const-qualified type T, T shall be a class type with a
2922 // user-provided default constructor.
2923 if (Kind.getKind() == InitializationKind::IK_Default &&
2924 Entity.getType().isConstQualified() &&
2925 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2926 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2927 return;
2928 }
2929
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002930 // Add the constructor initialization step. Any cv-qualification conversion is
2931 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002932 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002934 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002935 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002936}
2937
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002938/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002940 const InitializedEntity &Entity,
2941 const InitializationKind &Kind,
2942 InitializationSequence &Sequence) {
2943 // C++ [dcl.init]p5:
2944 //
2945 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002946 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002948 // -- if T is an array type, then each element is value-initialized;
2949 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2950 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002952 if (const RecordType *RT = T->getAs<RecordType>()) {
2953 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2954 // -- if T is a class type (clause 9) with a user-declared
2955 // constructor (12.1), then the default constructor for T is
2956 // called (and the initialization is ill-formed if T has no
2957 // accessible default constructor);
2958 //
2959 // FIXME: we really want to refer to a single subobject of the array,
2960 // but Entity doesn't have a way to capture that (yet).
2961 if (ClassDecl->hasUserDeclaredConstructor())
2962 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002964 // -- if T is a (possibly cv-qualified) non-union class type
2965 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002966 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002967 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002968 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002969 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002970 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002972 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002973 }
2974 }
2975
Douglas Gregor1b303932009-12-22 15:35:07 +00002976 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002977}
2978
Douglas Gregor85dabae2009-12-16 01:38:02 +00002979/// \brief Attempt default initialization (C++ [dcl.init]p6).
2980static void TryDefaultInitialization(Sema &S,
2981 const InitializedEntity &Entity,
2982 const InitializationKind &Kind,
2983 InitializationSequence &Sequence) {
2984 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985
Douglas Gregor85dabae2009-12-16 01:38:02 +00002986 // C++ [dcl.init]p6:
2987 // To default-initialize an object of type T means:
2988 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00002989 QualType DestType = S.Context.getBaseElementType(Entity.getType());
2990
Douglas Gregor85dabae2009-12-16 01:38:02 +00002991 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2992 // constructor for T is called (and the initialization is ill-formed if
2993 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002994 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002995 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2996 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998
Douglas Gregor85dabae2009-12-16 01:38:02 +00002999 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000
Douglas Gregor85dabae2009-12-16 01:38:02 +00003001 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003003 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003004 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003005 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003006 return;
3007 }
3008
3009 // If the destination type has a lifetime property, zero-initialize it.
3010 if (DestType.getQualifiers().hasObjCLifetime()) {
3011 Sequence.AddZeroInitializationStep(Entity.getType());
3012 return;
3013 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003014}
3015
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003016/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3017/// which enumerates all conversion functions and performs overload resolution
3018/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003020 const InitializedEntity &Entity,
3021 const InitializationKind &Kind,
3022 Expr *Initializer,
3023 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003024 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003025 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3026 QualType SourceType = Initializer->getType();
3027 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3028 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003029
Douglas Gregor540c3b02009-12-14 17:27:33 +00003030 // Build the candidate set directly in the initialization sequence
3031 // structure, so that it will persist if we fail.
3032 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3033 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003034
Douglas Gregor540c3b02009-12-14 17:27:33 +00003035 // Determine whether we are allowed to call explicit constructors or
3036 // explicit conversion operators.
3037 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003038
Douglas Gregor540c3b02009-12-14 17:27:33 +00003039 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3040 // The type we're converting to is a class type. Enumerate its constructors
3041 // to see if there is a suitable conversion.
3042 CXXRecordDecl *DestRecordDecl
3043 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
Douglas Gregord9848152010-04-26 14:36:57 +00003045 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003047 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003048 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003049 Con != ConEnd; ++Con) {
3050 NamedDecl *D = *Con;
3051 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052
Douglas Gregord9848152010-04-26 14:36:57 +00003053 // Find the constructor (which may be a template).
3054 CXXConstructorDecl *Constructor = 0;
3055 FunctionTemplateDecl *ConstructorTmpl
3056 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003057 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003058 Constructor = cast<CXXConstructorDecl>(
3059 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003060 else
Douglas Gregord9848152010-04-26 14:36:57 +00003061 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062
Douglas Gregord9848152010-04-26 14:36:57 +00003063 if (!Constructor->isInvalidDecl() &&
3064 Constructor->isConvertingConstructor(AllowExplicit)) {
3065 if (ConstructorTmpl)
3066 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3067 /*ExplicitArgs*/ 0,
3068 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003069 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003070 else
3071 S.AddOverloadCandidate(Constructor, FoundDecl,
3072 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003073 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075 }
Douglas Gregord9848152010-04-26 14:36:57 +00003076 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003077 }
Eli Friedman78275202009-12-19 08:11:05 +00003078
3079 SourceLocation DeclLoc = Initializer->getLocStart();
3080
Douglas Gregor540c3b02009-12-14 17:27:33 +00003081 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3082 // The type we're converting from is a class type, enumerate its conversion
3083 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003084
Eli Friedman4afe9a32009-12-20 22:12:03 +00003085 // We can only enumerate the conversion functions for a complete type; if
3086 // the type isn't complete, simply skip this step.
3087 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3088 CXXRecordDecl *SourceRecordDecl
3089 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090
John McCallad371252010-01-20 00:46:10 +00003091 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003092 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003093 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003095 I != E; ++I) {
3096 NamedDecl *D = *I;
3097 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3098 if (isa<UsingShadowDecl>(D))
3099 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100
Eli Friedman4afe9a32009-12-20 22:12:03 +00003101 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3102 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003103 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003104 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003105 else
John McCallda4458e2010-03-31 01:36:47 +00003106 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107
Eli Friedman4afe9a32009-12-20 22:12:03 +00003108 if (AllowExplicit || !Conv->isExplicit()) {
3109 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003110 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003111 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003112 CandidateSet);
3113 else
John McCalla0296f72010-03-19 07:35:19 +00003114 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003115 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003116 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003117 }
3118 }
3119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120
3121 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003122 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003123 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003124 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003125 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003127 Result);
3128 return;
3129 }
John McCall0d1da222010-01-12 00:44:57 +00003130
Douglas Gregor540c3b02009-12-14 17:27:33 +00003131 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003132 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133
Douglas Gregor540c3b02009-12-14 17:27:33 +00003134 if (isa<CXXConstructorDecl>(Function)) {
3135 // Add the user-defined conversion step. Any cv-qualification conversion is
3136 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003137 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003138 return;
3139 }
3140
3141 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003142 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003143 if (ConvType->getAs<RecordType>()) {
3144 // If we're converting to a class type, there may be an copy if
3145 // the resulting temporary object (possible to create an object of
3146 // a base class type). That copy is not a separate conversion, so
3147 // we just make a note of the actual destination type (possibly a
3148 // base class of the type returned by the conversion function) and
3149 // let the user-defined conversion step handle the conversion.
3150 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3151 return;
3152 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003153
Douglas Gregor5ab11652010-04-17 22:01:05 +00003154 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155
Douglas Gregor5ab11652010-04-17 22:01:05 +00003156 // If the conversion following the call to the conversion function
3157 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003158 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3159 Best->FinalConversion.Third) {
3160 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003161 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003162 ICS.Standard = Best->FinalConversion;
3163 Sequence.AddConversionSequenceStep(ICS, DestType);
3164 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003165}
3166
John McCall31168b02011-06-15 23:02:42 +00003167/// The non-zero enum values here are indexes into diagnostic alternatives.
3168enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3169
3170/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003171static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3172 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003173 // Skip parens.
3174 e = e->IgnoreParens();
3175
3176 // Skip address-of nodes.
3177 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3178 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003179 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003180
3181 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003182 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3183 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003184 case CK_Dependent:
3185 case CK_BitCast:
3186 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003187 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003188 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003189
3190 case CK_ArrayToPointerDecay:
3191 return IIK_nonscalar;
3192
3193 case CK_NullToPointer:
3194 return IIK_okay;
3195
3196 default:
3197 break;
3198 }
3199
3200 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003201 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3202 if (!isAddressOf) return IIK_nonlocal;
3203
3204 VarDecl *var;
3205 if (isa<DeclRefExpr>(e)) {
3206 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3207 if (!var) return IIK_nonlocal;
3208 } else {
3209 var = cast<BlockDeclRefExpr>(e)->getDecl();
3210 }
3211
3212 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003213
3214 // If we have a conditional operator, check both sides.
3215 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003216 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003217 return iik;
3218
John McCall63f84442011-06-27 23:59:58 +00003219 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003220
3221 // These are never scalar.
3222 } else if (isa<ArraySubscriptExpr>(e)) {
3223 return IIK_nonscalar;
3224
3225 // Otherwise, it needs to be a null pointer constant.
3226 } else {
3227 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3228 ? IIK_okay : IIK_nonlocal);
3229 }
3230
3231 return IIK_nonlocal;
3232}
3233
3234/// Check whether the given expression is a valid operand for an
3235/// indirect copy/restore.
3236static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3237 assert(src->isRValue());
3238
John McCall63f84442011-06-27 23:59:58 +00003239 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003240 if (iik == IIK_okay) return;
3241
3242 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3243 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3244 << src->getSourceRange();
3245}
3246
Sebastian Redl9c618092011-07-14 19:08:10 +00003247static bool hasDefaultConstructor(Sema &S, CXXRecordDecl *decl) {
3248 DeclContext::lookup_const_iterator Con, ConEnd;
3249 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(decl);
3250 Con != ConEnd; ++Con) {
3251 // FIXME: A constructor template can be a default constructor, but we don't
3252 // handle this in other places as well.
3253 if (isa<FunctionTemplateDecl>(*Con))
3254 continue;
3255 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3256 if (Constructor->isDefaultConstructor())
3257 return true;
3258 }
3259 return false;
3260}
3261
3262/// \brief Attempt list initialization (C++0x [dcl.init.list])
3263static void TryListInitialization(Sema &S,
3264 const InitializedEntity &Entity,
3265 const InitializationKind &Kind,
3266 InitListExpr *InitList,
3267 InitializationSequence &Sequence) {
3268 QualType DestType = Entity.getType();
3269
3270 // If we're not in C++ mode, defer everything to the init list checker.
3271 if (!S.getLangOptions().CPlusPlus) {
3272 Sequence.AddListInitializationStep(DestType);
3273 return;
3274 }
3275
3276 // Early error return for some C++11 features when we're in 98 mode.
3277 if (!S.getLangOptions().CPlusPlus0x) {
3278 if (DestType->isReferenceType()) {
3279 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3280 return;
3281 }
3282 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3283 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3284 return;
3285 }
3286 }
3287
3288 // If we have a reference and not exactly one initializer (see below), unwrap
3289 // the reference.
3290 bool wasReference = false;
3291 if (InitList->getNumInits() != 1) {
3292 if (const ReferenceType *ref = DestType->getAs<ReferenceType>()) {
3293 wasReference = true;
3294 DestType = ref->getPointeeType();
3295 }
3296 }
3297 // Create an object that automatically adds a ref binding step on successful
3298 // return.
3299 class AddRefBinding {
3300 InitializationSequence &Sequence;
3301 bool Bind;
3302 QualType RefType;
3303 public:
3304 AddRefBinding(InitializationSequence &sequence, bool bind, QualType refType)
3305 : Sequence(sequence), Bind(bind), RefType(refType) {}
3306 ~AddRefBinding() {
3307 if (Bind && Sequence) {
3308 Sequence.AddReferenceBindingStep(RefType, /*temporary*/true);
3309 }
3310 }
3311 } addRefBinding(Sequence, wasReference, Entity.getType());
3312
3313 // C++11 [dcl.init.list]p3:
3314 // List-initialization of an object or reference of type T is defined as
3315 // follows:
3316 //
3317 // - If the initializer list has no elements and T is a class type with
3318 // a default constructor, the object is value-initialized.
3319 //
3320 // See DR990. This case is handled specially because if we let it get to
3321 // overload resolution, std::initializer_list constructors would be chosen
3322 // over the default constructor. When there's more than one initlist ctor,
3323 // this would actually be ambiguous and fail.
3324
3325 const RecordType *recordType = DestType->getAs<RecordType>();
3326 CXXRecordDecl *recordDecl = recordType ?
3327 dyn_cast<CXXRecordDecl>(recordType->getDecl()) : 0;
3328 if (recordDecl && InitList->getNumInits() == 0 &&
3329 hasDefaultConstructor(S, recordDecl)) {
3330 TryValueInitialization(S, Entity, Kind, Sequence);
3331 return;
3332 }
3333
3334 // - Otherwise, if T is an aggregate, aggregate initialization is
3335 // performed.
3336 //
3337 // Aggregate initialization is the most complicated part. We delegate to
3338 // an InitListChecker to build a representation of what's happening.
3339 // We also treat vector types the same as aggregates.
3340 if (DestType->isAggregateType() || DestType->isVectorType()) {
3341 // FIXME: Deeper analysis necessary.
3342 Sequence.AddListInitializationStep(DestType);
3343 return;
3344 }
3345
3346 // - Otherwise, if T is a specialization of std::initializer_list<E>, an
3347 // initializer_list object is constructed as described below and used
3348 // to initialize the object according to the rules for initialization
3349 // of an object from a class of the same type.
3350 //
3351 // FIXME: Implement this case.
3352
3353 // - Otherwise, if T is a class type, constructors are considered. The
3354 // applicable constructors are enumerated and the best one is chosen
3355 // through overload resolution.
3356 if (recordDecl) {
3357 // FIXME: initializer_list constructors are applicable.
3358 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3359 InitList->getNumInits(), DestType, Sequence);
3360 return;
3361 }
3362
3363 // At this point, there is most likely a defect in the standard. The next
3364 // bullet grabs all reference targets and creates temporaries from the init
3365 // list. However, this means that code such as this doesn't work:
3366 // int i;
3367 // int &ri { i }; // error: non-const lvalue ref cannot bind to temporary.
3368 // This is rather startling, since this code works:
3369 // int &si ( i );
3370 //
3371 // DR934 (CD2 status) tried to address the problem by making the bullet about
3372 // references be only about references to class types, letting references to
3373 // other things fall through. This means the above works, but this still
3374 // doesn't:
3375 // string s;
3376 // string &rs { s }; // cannot bind to temporary
3377 // string &ss ( s ); // fine
3378 // And this works, but has different semantics:
3379 // const string &cs { s }; // binds to temporary copy
3380 // const string &ds ( s ); // binds directly to s
3381 // Also, the wording change from that DR somehow got lost in the FDIS.
3382 //
3383 // DR1095 (FDIS status) again discovered the problem, but didn't actually
3384 // fix it.
3385 //
3386 // GCC implements it this way. We swap the next two bullets instead, thus
3387 // always letting a reference bind to the single element of an initializer
3388 // list, and constructing a temporary only if the isn't exactly one element.
3389 // So in our order, the next bullet is:
3390 //
3391 // - Otherwise, if the initializer list has a single element, the object
3392 // or reference is initialized from that element;
3393 if (InitList->getNumInits() == 1) {
3394 SelectInitialization(S, Entity, Kind, InitList->getInits(),
3395 InitList->getNumInits(), Sequence);
3396 // Adjust the type of the whole init list to be the same as that of the
3397 // single initializer.
3398 InitList->setType(InitList->getInits()[0]->getType());
3399 return;
3400 }
3401
3402 // - Otherwise, if T is a reference type, a prvalue temporary of the type
3403 // referenced by T is list-initialized, and the reference is bound to
3404 // that temporary.
3405 //
3406 // We implement this by unwrapping references at the start of the function
3407 // and adding a reference binding step at the bottom.
3408
3409 // - Otherwise, if the initializer list has no elements, the object is
3410 // value-initialized.
3411 if (InitList->getNumInits() == 0) {
3412 TryValueInitialization(S, Entity, Kind, Sequence);
3413 return;
3414 }
3415
3416 // - Otherwise, the program is ill-formed.
3417 //
3418 // The only way to get here ought to be for scalar types with > 1 inits.
3419 assert(DestType->isScalarType() && "Something strange is list-initialized.");
3420 assert(InitList->getNumInits() > 1 && "Strange number of initializers.");
3421
3422 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3423 return;
3424}
3425
Douglas Gregore2f943b2011-02-22 18:29:51 +00003426/// \brief Determine whether we have compatible array types for the
3427/// purposes of GNU by-copy array initialization.
3428static bool hasCompatibleArrayTypes(ASTContext &Context,
3429 const ArrayType *Dest,
3430 const ArrayType *Source) {
3431 // If the source and destination array types are equivalent, we're
3432 // done.
3433 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3434 return true;
3435
3436 // Make sure that the element types are the same.
3437 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3438 return false;
3439
3440 // The only mismatch we allow is when the destination is an
3441 // incomplete array type and the source is a constant array type.
3442 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3443}
3444
John McCall31168b02011-06-15 23:02:42 +00003445static bool tryObjCWritebackConversion(Sema &S,
3446 InitializationSequence &Sequence,
3447 const InitializedEntity &Entity,
3448 Expr *Initializer) {
3449 bool ArrayDecay = false;
3450 QualType ArgType = Initializer->getType();
3451 QualType ArgPointee;
3452 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3453 ArrayDecay = true;
3454 ArgPointee = ArgArrayType->getElementType();
3455 ArgType = S.Context.getPointerType(ArgPointee);
3456 }
3457
3458 // Handle write-back conversion.
3459 QualType ConvertedArgType;
3460 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3461 ConvertedArgType))
3462 return false;
3463
3464 // We should copy unless we're passing to an argument explicitly
3465 // marked 'out'.
3466 bool ShouldCopy = true;
3467 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3468 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3469
3470 // Do we need an lvalue conversion?
3471 if (ArrayDecay || Initializer->isGLValue()) {
3472 ImplicitConversionSequence ICS;
3473 ICS.setStandard();
3474 ICS.Standard.setAsIdentityConversion();
3475
3476 QualType ResultType;
3477 if (ArrayDecay) {
3478 ICS.Standard.First = ICK_Array_To_Pointer;
3479 ResultType = S.Context.getPointerType(ArgPointee);
3480 } else {
3481 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3482 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3483 }
3484
3485 Sequence.AddConversionSequenceStep(ICS, ResultType);
3486 }
3487
3488 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3489 return true;
3490}
3491
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003492InitializationSequence::InitializationSequence(Sema &S,
3493 const InitializedEntity &Entity,
3494 const InitializationKind &Kind,
3495 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003496 unsigned NumArgs)
3497 : FailedCandidateSet(Kind.getLocation()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003499 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500 // The semantics of initializers are as follows. The destination type is
3501 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003502 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003504 // parenthesized list of expressions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003505
Sebastian Redl9c618092011-07-14 19:08:10 +00003506 if (Entity.getType()->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3508 SequenceKind = DependentSequence;
3509 return;
3510 }
3511
Sebastian Redld201edf2011-06-05 13:59:11 +00003512 // Almost everything is a normal sequence.
3513 setSequenceKind(NormalSequence);
3514
Sebastian Redl9c618092011-07-14 19:08:10 +00003515 SelectInitialization(S, Entity, Kind, Args, NumArgs, *this);
3516}
3517
3518static void SelectInitialization(Sema &S, const InitializedEntity &Entity,
3519 const InitializationKind &Kind,
3520 Expr **Args, unsigned NumArgs,
3521 InitializationSequence &Sequence) {
3522 ASTContext &Context = S.Context;
3523 QualType DestType = Entity.getType();
3524
John McCalled75c092010-12-07 22:54:16 +00003525 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003526 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3527 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3528 if (Result.isInvalid()) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003529 Sequence.SetFailed(
3530 InitializationSequence::FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003531 return;
3532 }
3533 Args[I] = Result.take();
3534 }
John McCalled75c092010-12-07 22:54:16 +00003535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003536 QualType SourceType;
3537 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003538 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003539 Initializer = Args[0];
3540 if (!isa<InitListExpr>(Initializer))
3541 SourceType = Initializer->getType();
3542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543
3544 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003545 // list-initialized (8.5.4).
3546 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003547 TryListInitialization(S, Entity, Kind, InitList, Sequence);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003548 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003551 // - If the destination type is a reference type, see 8.5.3.
3552 if (DestType->isReferenceType()) {
3553 // C++0x [dcl.init.ref]p1:
3554 // A variable declared to be a T& or T&&, that is, "reference to type T"
3555 // (8.3.2), shall be initialized by an object, or function, of type T or
3556 // by an object that can be converted into a T.
3557 // (Therefore, multiple arguments are not permitted.)
3558 if (NumArgs != 1)
Sebastian Redl9c618092011-07-14 19:08:10 +00003559 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560 else
Sebastian Redl9c618092011-07-14 19:08:10 +00003561 TryReferenceInitialization(S, Entity, Kind, Args[0], Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003562 return;
3563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003565 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003566 if (Kind.getKind() == InitializationKind::IK_Value ||
3567 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003568 TryValueInitialization(S, Entity, Kind, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003569 return;
3570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregor85dabae2009-12-16 01:38:02 +00003572 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003573 if (Kind.getKind() == InitializationKind::IK_Default) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003574 TryDefaultInitialization(S, Entity, Kind, Sequence);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003575 return;
3576 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003577
John McCall66884dd2011-02-21 07:22:22 +00003578 // - If the destination type is an array of characters, an array of
3579 // char16_t, an array of char32_t, or an array of wchar_t, and the
3580 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003583 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3584 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003585 TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence);
John McCall66884dd2011-02-21 07:22:22 +00003586 return;
3587 }
3588
Douglas Gregore2f943b2011-02-22 18:29:51 +00003589 // Note: as an GNU C extension, we allow initialization of an
3590 // array from a compound literal that creates an array of the same
3591 // type, so long as the initializer has no side effects.
3592 if (!S.getLangOptions().CPlusPlus && Initializer &&
3593 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3594 Initializer->getType()->isArrayType()) {
3595 const ArrayType *SourceAT
3596 = Context.getAsArrayType(Initializer->getType());
3597 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Sebastian Redl9c618092011-07-14 19:08:10 +00003598 Sequence.SetFailed(InitializationSequence::FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003599 else if (Initializer->HasSideEffects(S.Context))
Sebastian Redl9c618092011-07-14 19:08:10 +00003600 Sequence.SetFailed(InitializationSequence::FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003601 else {
Sebastian Redl9c618092011-07-14 19:08:10 +00003602 Sequence.AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003603 }
3604 } else if (DestAT->getElementType()->isAnyCharacterType())
Sebastian Redl9c618092011-07-14 19:08:10 +00003605 Sequence.SetFailed(
3606 InitializationSequence::FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003607 else
Sebastian Redl9c618092011-07-14 19:08:10 +00003608 Sequence.SetFailed(InitializationSequence::FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 return;
3611 }
Eli Friedman78275202009-12-19 08:11:05 +00003612
John McCall31168b02011-06-15 23:02:42 +00003613 // Determine whether we should consider writeback conversions for
3614 // Objective-C ARC.
3615 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3616 Entity.getKind() == InitializedEntity::EK_Parameter;
3617
3618 // We're at the end of the line for C: it's either a write-back conversion
3619 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003620 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003621 // If allowed, check whether this is an Objective-C writeback conversion.
3622 if (allowObjCWritebackConversion &&
Sebastian Redl9c618092011-07-14 19:08:10 +00003623 tryObjCWritebackConversion(S, Sequence, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003624 return;
3625 }
3626
3627 // Handle initialization in C
Sebastian Redl9c618092011-07-14 19:08:10 +00003628 Sequence.AddCAssignmentStep(DestType);
3629 MaybeProduceObjCObject(S, Sequence, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003630 return;
3631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632
John McCall31168b02011-06-15 23:02:42 +00003633 assert(S.getLangOptions().CPlusPlus);
3634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003635 // - If the destination type is a (possibly cv-qualified) class type:
3636 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637 // - If the initialization is direct-initialization, or if it is
3638 // copy-initialization where the cv-unqualified version of the
3639 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003640 // class of the destination, constructors are considered. [...]
3641 if (Kind.getKind() == InitializationKind::IK_Direct ||
3642 (Kind.getKind() == InitializationKind::IK_Copy &&
3643 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3644 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Sebastian Redl9c618092011-07-14 19:08:10 +00003646 Entity.getType(), Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650 // used) to a derived class thereof are enumerated as described in
3651 // 13.3.1.4, and the best one is chosen through overload resolution
3652 // (13.3).
3653 else
Sebastian Redl9c618092011-07-14 19:08:10 +00003654 TryUserDefinedConversion(S, Entity, Kind, Initializer, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003655 return;
3656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
Douglas Gregor85dabae2009-12-16 01:38:02 +00003658 if (NumArgs > 1) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003659 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003660 return;
3661 }
3662 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
3664 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003665 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003666 if (!SourceType.isNull() && SourceType->isRecordType()) {
Sebastian Redl9c618092011-07-14 19:08:10 +00003667 TryUserDefinedConversion(S, Entity, Kind, Initializer, Sequence);
3668 MaybeProduceObjCObject(S, Sequence, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003669 return;
3670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003673 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003674 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003676 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003677
3678 ImplicitConversionSequence ICS
3679 = S.TryImplicitConversion(Initializer, Entity.getType(),
3680 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003681 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003682 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003683 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3684 allowObjCWritebackConversion);
3685
3686 if (ICS.isStandard() &&
3687 ICS.Standard.Second == ICK_Writeback_Conversion) {
3688 // Objective-C ARC writeback conversion.
3689
3690 // We should copy unless we're passing to an argument explicitly
3691 // marked 'out'.
3692 bool ShouldCopy = true;
3693 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3694 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3695
3696 // If there was an lvalue adjustment, add it as a separate conversion.
3697 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3698 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3699 ImplicitConversionSequence LvalueICS;
3700 LvalueICS.setStandard();
3701 LvalueICS.Standard.setAsIdentityConversion();
3702 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3703 LvalueICS.Standard.First = ICS.Standard.First;
Sebastian Redl9c618092011-07-14 19:08:10 +00003704 Sequence.AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003705 }
Sebastian Redl9c618092011-07-14 19:08:10 +00003706
3707 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003708 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003709 DeclAccessPair dap;
3710 if (Initializer->getType() == Context.OverloadTy &&
3711 !S.ResolveAddressOfOverloadedFunction(Initializer
3712 , DestType, false, dap))
Sebastian Redl9c618092011-07-14 19:08:10 +00003713 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003714 else
Sebastian Redl9c618092011-07-14 19:08:10 +00003715 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003716 } else {
Sebastian Redl9c618092011-07-14 19:08:10 +00003717 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003718
Sebastian Redl9c618092011-07-14 19:08:10 +00003719 MaybeProduceObjCObject(S, Sequence, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003720 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003721}
3722
3723InitializationSequence::~InitializationSequence() {
3724 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3725 StepEnd = Steps.end();
3726 Step != StepEnd; ++Step)
3727 Step->Destroy();
3728}
3729
3730//===----------------------------------------------------------------------===//
3731// Perform initialization
3732//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003734getAssignmentAction(const InitializedEntity &Entity) {
3735 switch(Entity.getKind()) {
3736 case InitializedEntity::EK_Variable:
3737 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003738 case InitializedEntity::EK_Exception:
3739 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003740 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003741 return Sema::AA_Initializing;
3742
3743 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003745 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3746 return Sema::AA_Sending;
3747
Douglas Gregore1314a62009-12-18 05:02:21 +00003748 return Sema::AA_Passing;
3749
3750 case InitializedEntity::EK_Result:
3751 return Sema::AA_Returning;
3752
Douglas Gregore1314a62009-12-18 05:02:21 +00003753 case InitializedEntity::EK_Temporary:
3754 // FIXME: Can we tell apart casting vs. converting?
3755 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Douglas Gregore1314a62009-12-18 05:02:21 +00003757 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003758 case InitializedEntity::EK_ArrayElement:
3759 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003760 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003761 return Sema::AA_Initializing;
3762 }
3763
3764 return Sema::AA_Converting;
3765}
3766
Douglas Gregor95562572010-04-24 23:45:46 +00003767/// \brief Whether we should binding a created object as a temporary when
3768/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003769static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003770 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003771 case InitializedEntity::EK_ArrayElement:
3772 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003773 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003774 case InitializedEntity::EK_New:
3775 case InitializedEntity::EK_Variable:
3776 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003777 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003778 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003779 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003780 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003781 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782
Douglas Gregore1314a62009-12-18 05:02:21 +00003783 case InitializedEntity::EK_Parameter:
3784 case InitializedEntity::EK_Temporary:
3785 return true;
3786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Douglas Gregore1314a62009-12-18 05:02:21 +00003788 llvm_unreachable("missed an InitializedEntity kind?");
3789}
3790
Douglas Gregor95562572010-04-24 23:45:46 +00003791/// \brief Whether the given entity, when initialized with an object
3792/// created for that initialization, requires destruction.
3793static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3794 switch (Entity.getKind()) {
3795 case InitializedEntity::EK_Member:
3796 case InitializedEntity::EK_Result:
3797 case InitializedEntity::EK_New:
3798 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003799 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003800 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003801 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003802 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregor95562572010-04-24 23:45:46 +00003804 case InitializedEntity::EK_Variable:
3805 case InitializedEntity::EK_Parameter:
3806 case InitializedEntity::EK_Temporary:
3807 case InitializedEntity::EK_ArrayElement:
3808 case InitializedEntity::EK_Exception:
3809 return true;
3810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811
3812 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003813}
3814
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003815/// \brief Make a (potentially elidable) temporary copy of the object
3816/// provided by the given initializer by calling the appropriate copy
3817/// constructor.
3818///
3819/// \param S The Sema object used for type-checking.
3820///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003821/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003822/// the type of the initializer expression or a superclass thereof.
3823///
3824/// \param Enter The entity being initialized.
3825///
3826/// \param CurInit The initializer expression.
3827///
3828/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3829/// is permitted in C++03 (but not C++0x) when binding a reference to
3830/// an rvalue.
3831///
3832/// \returns An expression that copies the initializer expression into
3833/// a temporary object, or an error expression if a copy could not be
3834/// created.
John McCalldadc5752010-08-24 06:29:42 +00003835static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003836 QualType T,
3837 const InitializedEntity &Entity,
3838 ExprResult CurInit,
3839 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003840 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003841 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003843 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003844 Class = cast<CXXRecordDecl>(Record->getDecl());
3845 if (!Class)
3846 return move(CurInit);
3847
Douglas Gregor5d369002011-01-21 18:05:27 +00003848 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003849 // When certain criteria are met, an implementation is allowed to
3850 // omit the copy/move construction of a class object, even if the
3851 // copy/move constructor and/or destructor for the object have
3852 // side effects. [...]
3853 // - when a temporary class object that has not been bound to a
3854 // reference (12.2) would be copied/moved to a class object
3855 // with the same cv-unqualified type, the copy/move operation
3856 // can be omitted by constructing the temporary object
3857 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003859 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003860 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003862 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003863 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003864 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003865 switch (Entity.getKind()) {
3866 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003867 Loc = Entity.getReturnLoc();
3868 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
Douglas Gregore1314a62009-12-18 05:02:21 +00003870 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003871 Loc = Entity.getThrowLoc();
3872 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873
Douglas Gregore1314a62009-12-18 05:02:21 +00003874 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003875 Loc = Entity.getDecl()->getLocation();
3876 break;
3877
Anders Carlsson0bd52402010-01-24 00:19:41 +00003878 case InitializedEntity::EK_ArrayElement:
3879 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003880 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003881 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003882 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003883 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003884 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003885 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003886 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003887 Loc = CurInitExpr->getLocStart();
3888 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003889 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003890
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003892 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3893 return move(CurInit);
3894
Douglas Gregorf282a762011-01-21 19:38:21 +00003895 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003896 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003897 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003898 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003899 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003900 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003901 // C++0x [dcl.init]p16, second bullet to class types, this
3902 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003903 CXXConstructorDecl *Constructor = 0;
3904
3905 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003906 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003907 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003908 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003909 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003910 continue;
3911
3912 DeclAccessPair FoundDecl
3913 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3914 S.AddOverloadCandidate(Constructor, FoundDecl,
3915 &CurInitExpr, 1, CandidateSet);
3916 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003918
3919 // Handle constructor templates.
3920 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3921 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003922 continue;
John McCalla0296f72010-03-19 07:35:19 +00003923
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003924 Constructor = cast<CXXConstructorDecl>(
3925 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003926 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003927 continue;
3928
3929 // FIXME: Do we need to limit this to copy-constructor-like
3930 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003931 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003932 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3933 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3934 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936
Douglas Gregore1314a62009-12-18 05:02:21 +00003937 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003938 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003939 case OR_Success:
3940 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Douglas Gregore1314a62009-12-18 05:02:21 +00003942 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003943 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3944 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3945 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003946 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003947 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003948 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003949 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003950 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003951 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952
Douglas Gregore1314a62009-12-18 05:02:21 +00003953 case OR_Ambiguous:
3954 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003955 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003956 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003957 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003958 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003959
Douglas Gregore1314a62009-12-18 05:02:21 +00003960 case OR_Deleted:
3961 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003962 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003963 << CurInitExpr->getSourceRange();
3964 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00003965 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003966 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003967 }
3968
Douglas Gregor5ab11652010-04-17 22:01:05 +00003969 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003970 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003971 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003972
Anders Carlssona01874b2010-04-21 18:47:17 +00003973 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003974 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003975
3976 if (IsExtraneousCopy) {
3977 // If this is a totally extraneous copy for C++03 reference
3978 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003979 // expression. We don't generate an (elided) copy operation here
3980 // because doing so would require us to pass down a flag to avoid
3981 // infinite recursion, where each step adds another extraneous,
3982 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003983
Douglas Gregor30b52772010-04-18 07:57:34 +00003984 // Instantiate the default arguments of any extra parameters in
3985 // the selected copy constructor, as if we were going to create a
3986 // proper call to the copy constructor.
3987 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3988 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3989 if (S.RequireCompleteType(Loc, Parm->getType(),
3990 S.PDiag(diag::err_call_incomplete_argument)))
3991 break;
3992
3993 // Build the default argument expression; we don't actually care
3994 // if this succeeds or not, because this routine will complain
3995 // if there was a problem.
3996 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3997 }
3998
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003999 return S.Owned(CurInitExpr);
4000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001
Chandler Carruth30141632011-02-25 19:41:05 +00004002 S.MarkDeclarationReferenced(Loc, Constructor);
4003
Douglas Gregor5ab11652010-04-17 22:01:05 +00004004 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004005 // constructor call (we might have derived-to-base conversions, or
4006 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004007 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004008 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004009 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004010
Douglas Gregord0ace022010-04-25 00:55:24 +00004011 // Actually perform the constructor call.
4012 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004013 move_arg(ConstructorArgs),
4014 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004015 CXXConstructExpr::CK_Complete,
4016 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017
Douglas Gregord0ace022010-04-25 00:55:24 +00004018 // If we're supposed to bind temporaries, do so.
4019 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4020 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4021 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004022}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004023
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004024void InitializationSequence::PrintInitLocationNote(Sema &S,
4025 const InitializedEntity &Entity) {
4026 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4027 if (Entity.getDecl()->getLocation().isInvalid())
4028 return;
4029
4030 if (Entity.getDecl()->getDeclName())
4031 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4032 << Entity.getDecl()->getDeclName();
4033 else
4034 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4035 }
4036}
4037
Sebastian Redl112aa822011-07-14 19:07:55 +00004038static bool isReferenceBinding(const InitializationSequence::Step &s) {
4039 return s.Kind == InitializationSequence::SK_BindReference ||
4040 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4041}
4042
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004044InitializationSequence::Perform(Sema &S,
4045 const InitializedEntity &Entity,
4046 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004047 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004048 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004049 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004050 unsigned NumArgs = Args.size();
4051 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004052 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054
Sebastian Redld201edf2011-06-05 13:59:11 +00004055 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004056 // If the declaration is a non-dependent, incomplete array type
4057 // that has an initializer, then its type will be completed once
4058 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004059 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004060 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004061 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004062 if (const IncompleteArrayType *ArrayT
4063 = S.Context.getAsIncompleteArrayType(DeclType)) {
4064 // FIXME: We don't currently have the ability to accurately
4065 // compute the length of an initializer list without
4066 // performing full type-checking of the initializer list
4067 // (since we have to determine where braces are implicitly
4068 // introduced and such). So, we fall back to making the array
4069 // type a dependently-sized array type with no specified
4070 // bound.
4071 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4072 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004073
Douglas Gregor51e77d52009-12-10 17:56:55 +00004074 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004075 if (DeclaratorDecl *DD = Entity.getDecl()) {
4076 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4077 TypeLoc TL = TInfo->getTypeLoc();
4078 if (IncompleteArrayTypeLoc *ArrayLoc
4079 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4080 Brackets = ArrayLoc->getBracketsRange();
4081 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004082 }
4083
4084 *ResultType
4085 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4086 /*NumElts=*/0,
4087 ArrayT->getSizeModifier(),
4088 ArrayT->getIndexTypeCVRQualifiers(),
4089 Brackets);
4090 }
4091
4092 }
4093 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004094 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4095 Kind.isExplicitCast());
4096 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004097 }
4098
Sebastian Redld201edf2011-06-05 13:59:11 +00004099 // No steps means no initialization.
4100 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004101 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102
Douglas Gregor1b303932009-12-22 15:35:07 +00004103 QualType DestType = Entity.getType().getNonReferenceType();
4104 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004105 // the same as Entity.getDecl()->getType() in cases involving type merging,
4106 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004107 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004108 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004109 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004110
John McCalldadc5752010-08-24 06:29:42 +00004111 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004114 // grab the only argument out the Args and place it into the "current"
4115 // initializer.
4116 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004117 case SK_ResolveAddressOfOverloadedFunction:
4118 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004119 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004120 case SK_CastDerivedToBaseLValue:
4121 case SK_BindReference:
4122 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004123 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004124 case SK_UserConversion:
4125 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004126 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004127 case SK_QualificationConversionRValue:
4128 case SK_ConversionSequence:
4129 case SK_ListInitialization:
4130 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004131 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004132 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004133 case SK_ArrayInit:
4134 case SK_PassByIndirectCopyRestore:
4135 case SK_PassByIndirectRestore:
4136 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004137 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004138 CurInit = Args.get()[0];
4139 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004140
4141 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004142 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4143 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4144 if (CurInit.isInvalid())
4145 return ExprError();
4146 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004147 break;
John McCall34376a62010-12-04 03:47:34 +00004148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004149
Douglas Gregore1314a62009-12-18 05:02:21 +00004150 case SK_ConstructorInitialization:
4151 case SK_ZeroInitialization:
4152 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
4155 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004157 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004158 for (step_iterator Step = step_begin(), StepEnd = step_end();
4159 Step != StepEnd; ++Step) {
4160 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004161 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
John Wiegley01296292011-04-08 18:41:53 +00004163 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004164
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004165 switch (Step->Kind) {
4166 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004168 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004169 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004170 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004171 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004172 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004173 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004176 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004177 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004178 case SK_CastDerivedToBaseLValue: {
4179 // We have a derived-to-base cast that produces either an rvalue or an
4180 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181
John McCallcf142162010-08-07 06:22:56 +00004182 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004183
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004184 // Casts to inaccessible base classes are allowed with C-style casts.
4185 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4186 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004187 CurInit.get()->getLocStart(),
4188 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004189 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004190 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191
Douglas Gregor88d292c2010-05-13 16:44:06 +00004192 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4193 QualType T = SourceType;
4194 if (const PointerType *Pointer = T->getAs<PointerType>())
4195 T = Pointer->getPointeeType();
4196 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004197 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004198 cast<CXXRecordDecl>(RecordTy->getDecl()));
4199 }
4200
John McCall2536c6d2010-08-25 10:28:54 +00004201 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004202 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004203 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004204 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004205 VK_XValue :
4206 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004207 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4208 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004209 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004210 CurInit.get(),
4211 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004212 break;
4213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004215 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004216 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004217 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4218 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004219 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004220 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004221 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004223 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004224 }
Anders Carlssona91be642010-01-29 02:47:33 +00004225
John Wiegley01296292011-04-08 18:41:53 +00004226 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004227 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004228 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4229 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004230 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004231 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004232 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004235 // Reference binding does not have any corresponding ASTs.
4236
4237 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004238 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004239 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004240
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004242
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004243 case SK_BindReferenceToTemporary:
4244 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004245 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004246 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004247
Douglas Gregorfe314812011-06-21 17:03:29 +00004248 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004249 CurInit = new (S.Context) MaterializeTemporaryExpr(
4250 Entity.getType().getNonReferenceType(),
4251 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004252 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004253
4254 // If we're binding to an Objective-C object that has lifetime, we
4255 // need cleanups.
4256 if (S.getLangOptions().ObjCAutoRefCount &&
4257 CurInit.get()->getType()->isObjCLifetimeType())
4258 S.ExprNeedsCleanups = true;
4259
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004260 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004262 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004264 /*IsExtraneousCopy=*/true);
4265 break;
4266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 case SK_UserConversion: {
4268 // We have a user-defined conversion that invokes either a constructor
4269 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004270 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004271 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004272 FunctionDecl *Fn = Step->Function.Function;
4273 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004274 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004275 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004276 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004277 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004278 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004279 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004282 // Determine the arguments required to actually perform the constructor
4283 // call.
John Wiegley01296292011-04-08 18:41:53 +00004284 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004286 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004287 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004288 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004289
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004290 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004292 move_arg(ConstructorArgs),
4293 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004294 CXXConstructExpr::CK_Complete,
4295 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004296 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004297 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004298
Anders Carlssona01874b2010-04-21 18:47:17 +00004299 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004300 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004301 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
John McCalle3027922010-08-25 11:45:40 +00004303 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004304 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4305 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4306 S.IsDerivedFrom(SourceType, Class))
4307 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor95562572010-04-24 23:45:46 +00004309 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004310 } else {
4311 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004312 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004313 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004314 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004315 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004316 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
4318 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004319 // derived-to-base conversion? I believe the answer is "no", because
4320 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004321 ExprResult CurInitExprRes =
4322 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4323 FoundFn, Conversion);
4324 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004325 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004326 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004328 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004329 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004330 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004331 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
John McCalle3027922010-08-25 11:45:40 +00004333 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Douglas Gregor95562572010-04-24 23:45:46 +00004335 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Sebastian Redl112aa822011-07-14 19:07:55 +00004338 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004339 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004340 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004341 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004342 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004343 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004345 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004346 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004347 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004348 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4349 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004350 }
4351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004353 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004354 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004355 CurInit.get()->getType(),
4356 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004357 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004359 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004360 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4361 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004362
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004363 break;
4364 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004365
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004366 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004367 case SK_QualificationConversionXValue:
4368 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004369 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004370 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004371 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004372 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004373 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004374 VK_XValue :
4375 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004376 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004377 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004378 }
4379
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004380 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004381 Sema::CheckedConversionKind CCK
4382 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4383 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4384 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4385 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004386 ExprResult CurInitExprRes =
4387 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004388 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004389 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004390 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004391 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004392 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregor51e77d52009-12-10 17:56:55 +00004395 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004396 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004397 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00004398 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00004399 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004400
4401 CurInit.release();
4402 CurInit = S.Owned(InitList);
4403 break;
4404 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004405
4406 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004407 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004408 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004409 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004411 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004412 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004413 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4414 ? Kind.getEqualLoc()
4415 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004416
4417 if (Kind.getKind() == InitializationKind::IK_Default) {
4418 // Force even a trivial, implicit default constructor to be
4419 // semantically checked. We do this explicitly because we don't build
4420 // the definition for completely trivial constructors.
4421 CXXRecordDecl *ClassDecl = Constructor->getParent();
4422 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004423 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004424 ClassDecl->hasTrivialDefaultConstructor() &&
4425 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004426 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4427 }
4428
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004429 // Determine the arguments required to actually perform the constructor
4430 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004432 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004433 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434
4435
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004436 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004437 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004438 (Kind.getKind() == InitializationKind::IK_Direct ||
4439 Kind.getKind() == InitializationKind::IK_Value)) {
4440 // An explicitly-constructed temporary, e.g., X(1, 2).
4441 unsigned NumExprs = ConstructorArgs.size();
4442 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004443 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004444 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445
Douglas Gregor2b88c112010-09-08 00:15:04 +00004446 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4447 if (!TSInfo)
4448 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004450 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4451 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004452 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004454 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004455 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004456 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004457 } else {
4458 CXXConstructExpr::ConstructionKind ConstructKind =
4459 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004461 if (Entity.getKind() == InitializedEntity::EK_Base) {
4462 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004464 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004465 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004466 ConstructKind = CXXConstructExpr::CK_Delegating;
4467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Chandler Carruth01718152010-10-25 08:47:36 +00004469 // Only get the parenthesis range if it is a direct construction.
4470 SourceRange parenRange =
4471 Kind.getKind() == InitializationKind::IK_Direct ?
4472 Kind.getParenRange() : SourceRange();
4473
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004474 // If the entity allows NRVO, mark the construction as elidable
4475 // unconditionally.
4476 if (Entity.allowsNRVO())
4477 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4478 Constructor, /*Elidable=*/true,
4479 move_arg(ConstructorArgs),
4480 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004481 ConstructKind,
4482 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004483 else
4484 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004486 move_arg(ConstructorArgs),
4487 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004488 ConstructKind,
4489 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004490 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004491 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004492 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004493
4494 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004495 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004496 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004497 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004499 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004500 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004502 break;
4503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004505 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004506 step_iterator NextStep = Step;
4507 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004509 NextStep->Kind == SK_ConstructorInitialization) {
4510 // The need for zero-initialization is recorded directly into
4511 // the call to the object's constructor within the next step.
4512 ConstructorInitRequiresZeroInit = true;
4513 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4514 S.getLangOptions().CPlusPlus &&
4515 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004516 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4517 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004519 Kind.getRange().getBegin());
4520
4521 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4522 TSInfo->getType().getNonLValueExprType(S.Context),
4523 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004524 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004525 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004526 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004527 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004528 break;
4529 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004530
4531 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004532 QualType SourceType = CurInit.get()->getType();
4533 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004534 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004535 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4536 if (Result.isInvalid())
4537 return ExprError();
4538 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004539
4540 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004541 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004542 if (ConvTy != Sema::Compatible &&
4543 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004544 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004545 == Sema::Compatible)
4546 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004547 if (CurInitExprRes.isInvalid())
4548 return ExprError();
4549 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004550
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004551 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004552 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4553 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004554 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004555 getAssignmentAction(Entity),
4556 &Complained)) {
4557 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004558 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004559 } else if (Complained)
4560 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004561 break;
4562 }
Eli Friedman78275202009-12-19 08:11:05 +00004563
4564 case SK_StringInit: {
4565 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004566 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004567 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004568 break;
4569 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004570
4571 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004572 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004573 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004574 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004575 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004576
4577 case SK_ArrayInit:
4578 // Okay: we checked everything before creating this step. Note that
4579 // this is a GNU extension.
4580 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004581 << Step->Type << CurInit.get()->getType()
4582 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004583
4584 // If the destination type is an incomplete array type, update the
4585 // type accordingly.
4586 if (ResultType) {
4587 if (const IncompleteArrayType *IncompleteDest
4588 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4589 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004590 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004591 *ResultType = S.Context.getConstantArrayType(
4592 IncompleteDest->getElementType(),
4593 ConstantSource->getSize(),
4594 ArrayType::Normal, 0);
4595 }
4596 }
4597 }
John McCall31168b02011-06-15 23:02:42 +00004598 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004599
John McCall31168b02011-06-15 23:02:42 +00004600 case SK_PassByIndirectCopyRestore:
4601 case SK_PassByIndirectRestore:
4602 checkIndirectCopyRestoreSource(S, CurInit.get());
4603 CurInit = S.Owned(new (S.Context)
4604 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4605 Step->Kind == SK_PassByIndirectCopyRestore));
4606 break;
4607
4608 case SK_ProduceObjCObject:
4609 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4610 CK_ObjCProduceObject,
4611 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004612 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004613 }
4614 }
John McCall1f425642010-11-11 03:21:53 +00004615
4616 // Diagnose non-fatal problems with the completed initialization.
4617 if (Entity.getKind() == InitializedEntity::EK_Member &&
4618 cast<FieldDecl>(Entity.getDecl())->isBitField())
4619 S.CheckBitFieldInitialization(Kind.getLocation(),
4620 cast<FieldDecl>(Entity.getDecl()),
4621 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004623 return move(CurInit);
4624}
4625
4626//===----------------------------------------------------------------------===//
4627// Diagnose initialization failures
4628//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004630 const InitializedEntity &Entity,
4631 const InitializationKind &Kind,
4632 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004633 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004634 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor1b303932009-12-22 15:35:07 +00004636 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004637 switch (Failure) {
4638 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004639 // FIXME: Customize for the initialized entity?
4640 if (NumArgs == 0)
4641 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4642 << DestType.getNonReferenceType();
4643 else // FIXME: diagnostic below could be better!
4644 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4645 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004646 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004648 case FK_ArrayNeedsInitList:
4649 case FK_ArrayNeedsInitListOrStringLiteral:
4650 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4651 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4652 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653
Douglas Gregore2f943b2011-02-22 18:29:51 +00004654 case FK_ArrayTypeMismatch:
4655 case FK_NonConstantArrayInit:
4656 S.Diag(Kind.getLocation(),
4657 (Failure == FK_ArrayTypeMismatch
4658 ? diag::err_array_init_different_type
4659 : diag::err_array_init_non_constant_array))
4660 << DestType.getNonReferenceType()
4661 << Args[0]->getType()
4662 << Args[0]->getSourceRange();
4663 break;
4664
John McCall16df1e52010-03-30 21:47:33 +00004665 case FK_AddressOfOverloadFailed: {
4666 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004668 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004669 true,
4670 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004671 break;
John McCall16df1e52010-03-30 21:47:33 +00004672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004674 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004675 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004676 switch (FailedOverloadResult) {
4677 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004678 if (Failure == FK_UserConversionOverloadFailed)
4679 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4680 << Args[0]->getType() << DestType
4681 << Args[0]->getSourceRange();
4682 else
4683 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4684 << DestType << Args[0]->getType()
4685 << Args[0]->getSourceRange();
4686
John McCall5c32be02010-08-24 20:38:10 +00004687 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004688 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004690 case OR_No_Viable_Function:
4691 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4692 << Args[0]->getType() << DestType.getNonReferenceType()
4693 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004694 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004696
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004697 case OR_Deleted: {
4698 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4699 << Args[0]->getType() << DestType.getNonReferenceType()
4700 << Args[0]->getSourceRange();
4701 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004702 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004703 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4704 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004705 if (Ovl == OR_Deleted) {
4706 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004707 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004708 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004709 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004710 }
4711 break;
4712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004714 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004715 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004716 break;
4717 }
4718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004720 case FK_NonConstLValueReferenceBindingToTemporary:
4721 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004723 Failure == FK_NonConstLValueReferenceBindingToTemporary
4724 ? diag::err_lvalue_reference_bind_to_temporary
4725 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004726 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004727 << DestType.getNonReferenceType()
4728 << Args[0]->getType()
4729 << Args[0]->getSourceRange();
4730 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004732 case FK_RValueReferenceBindingToLValue:
4733 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004734 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004735 << Args[0]->getSourceRange();
4736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004738 case FK_ReferenceInitDropsQualifiers:
4739 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4740 << DestType.getNonReferenceType()
4741 << Args[0]->getType()
4742 << Args[0]->getSourceRange();
4743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004745 case FK_ReferenceInitFailed:
4746 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4747 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004748 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004749 << Args[0]->getType()
4750 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004751 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4752 Args[0]->getType()->isObjCObjectPointerType())
4753 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004754 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755
Douglas Gregorb491ed32011-02-19 21:32:49 +00004756 case FK_ConversionFailed: {
4757 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004758 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4759 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004760 << DestType
John McCall086a4642010-11-24 05:12:34 +00004761 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004762 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004763 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004764 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4765 Args[0]->getType()->isObjCObjectPointerType())
4766 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004767 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004768 }
John Wiegley01296292011-04-08 18:41:53 +00004769
4770 case FK_ConversionFromPropertyFailed:
4771 // No-op. This error has already been reported.
4772 break;
4773
Douglas Gregor51e77d52009-12-10 17:56:55 +00004774 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004775 SourceRange R;
4776
4777 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004778 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004779 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004781 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004782
Douglas Gregor8ec51732010-09-08 21:40:08 +00004783 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4784 if (Kind.isCStyleOrFunctionalCast())
4785 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4786 << R;
4787 else
4788 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4789 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004790 break;
4791 }
4792
4793 case FK_ReferenceBindingToInitList:
4794 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4795 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4796 break;
4797
4798 case FK_InitListBadDestinationType:
4799 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4800 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4801 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004803 case FK_ConstructorOverloadFailed: {
4804 SourceRange ArgsRange;
4805 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004807 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004809 // FIXME: Using "DestType" for the entity we're printing is probably
4810 // bad.
4811 switch (FailedOverloadResult) {
4812 case OR_Ambiguous:
4813 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4814 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004815 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4816 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004817 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004819 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004820 if (Kind.getKind() == InitializationKind::IK_Default &&
4821 (Entity.getKind() == InitializedEntity::EK_Base ||
4822 Entity.getKind() == InitializedEntity::EK_Member) &&
4823 isa<CXXConstructorDecl>(S.CurContext)) {
4824 // This is implicit default initialization of a member or
4825 // base within a constructor. If no viable function was
4826 // found, notify the user that she needs to explicitly
4827 // initialize this base/member.
4828 CXXConstructorDecl *Constructor
4829 = cast<CXXConstructorDecl>(S.CurContext);
4830 if (Entity.getKind() == InitializedEntity::EK_Base) {
4831 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4832 << Constructor->isImplicit()
4833 << S.Context.getTypeDeclType(Constructor->getParent())
4834 << /*base=*/0
4835 << Entity.getType();
4836
4837 RecordDecl *BaseDecl
4838 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4839 ->getDecl();
4840 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4841 << S.Context.getTagDeclType(BaseDecl);
4842 } else {
4843 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4844 << Constructor->isImplicit()
4845 << S.Context.getTypeDeclType(Constructor->getParent())
4846 << /*member=*/1
4847 << Entity.getName();
4848 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4849
4850 if (const RecordType *Record
4851 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004853 diag::note_previous_decl)
4854 << S.Context.getTagDeclType(Record->getDecl());
4855 }
4856 break;
4857 }
4858
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004859 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4860 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004861 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004862 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004864 case OR_Deleted: {
4865 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4866 << true << DestType << ArgsRange;
4867 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004868 OverloadingResult Ovl
4869 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004870 if (Ovl == OR_Deleted) {
4871 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004872 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004873 } else {
4874 llvm_unreachable("Inconsistent overload resolution?");
4875 }
4876 break;
4877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004878
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004879 case OR_Success:
4880 llvm_unreachable("Conversion did not fail!");
4881 break;
4882 }
4883 break;
4884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor85dabae2009-12-16 01:38:02 +00004886 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004887 if (Entity.getKind() == InitializedEntity::EK_Member &&
4888 isa<CXXConstructorDecl>(S.CurContext)) {
4889 // This is implicit default-initialization of a const member in
4890 // a constructor. Complain that it needs to be explicitly
4891 // initialized.
4892 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4893 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4894 << Constructor->isImplicit()
4895 << S.Context.getTypeDeclType(Constructor->getParent())
4896 << /*const=*/1
4897 << Entity.getName();
4898 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4899 << Entity.getName();
4900 } else {
4901 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4902 << DestType << (bool)DestType->getAs<RecordType>();
4903 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004904 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004905
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004906 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004907 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004908 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004909 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004912 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004913 return true;
4914}
Douglas Gregore1314a62009-12-18 05:02:21 +00004915
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004916void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4917 switch (SequenceKind) {
4918 case FailedSequence: {
4919 OS << "Failed sequence: ";
4920 switch (Failure) {
4921 case FK_TooManyInitsForReference:
4922 OS << "too many initializers for reference";
4923 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004925 case FK_ArrayNeedsInitList:
4926 OS << "array requires initializer list";
4927 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004929 case FK_ArrayNeedsInitListOrStringLiteral:
4930 OS << "array requires initializer list or string literal";
4931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregore2f943b2011-02-22 18:29:51 +00004933 case FK_ArrayTypeMismatch:
4934 OS << "array type mismatch";
4935 break;
4936
4937 case FK_NonConstantArrayInit:
4938 OS << "non-constant array initializer";
4939 break;
4940
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004941 case FK_AddressOfOverloadFailed:
4942 OS << "address of overloaded function failed";
4943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004945 case FK_ReferenceInitOverloadFailed:
4946 OS << "overload resolution for reference initialization failed";
4947 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004948
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004949 case FK_NonConstLValueReferenceBindingToTemporary:
4950 OS << "non-const lvalue reference bound to temporary";
4951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004952
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004953 case FK_NonConstLValueReferenceBindingToUnrelated:
4954 OS << "non-const lvalue reference bound to unrelated type";
4955 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004957 case FK_RValueReferenceBindingToLValue:
4958 OS << "rvalue reference bound to an lvalue";
4959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004961 case FK_ReferenceInitDropsQualifiers:
4962 OS << "reference initialization drops qualifiers";
4963 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004965 case FK_ReferenceInitFailed:
4966 OS << "reference initialization failed";
4967 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004969 case FK_ConversionFailed:
4970 OS << "conversion failed";
4971 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972
John Wiegley01296292011-04-08 18:41:53 +00004973 case FK_ConversionFromPropertyFailed:
4974 OS << "conversion from property failed";
4975 break;
4976
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004977 case FK_TooManyInitsForScalar:
4978 OS << "too many initializers for scalar";
4979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004981 case FK_ReferenceBindingToInitList:
4982 OS << "referencing binding to initializer list";
4983 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004984
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004985 case FK_InitListBadDestinationType:
4986 OS << "initializer list for non-aggregate, non-scalar type";
4987 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004989 case FK_UserConversionOverloadFailed:
4990 OS << "overloading failed for user-defined conversion";
4991 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004993 case FK_ConstructorOverloadFailed:
4994 OS << "constructor overloading failed";
4995 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004997 case FK_DefaultInitOfConst:
4998 OS << "default initialization of a const variable";
4999 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005001 case FK_Incomplete:
5002 OS << "initialization of incomplete type";
5003 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005005 OS << '\n';
5006 return;
5007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005009 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005010 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005011 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
Sebastian Redld201edf2011-06-05 13:59:11 +00005013 case NormalSequence:
5014 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005015 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005018 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5019 if (S != step_begin()) {
5020 OS << " -> ";
5021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005023 switch (S->Kind) {
5024 case SK_ResolveAddressOfOverloadedFunction:
5025 OS << "resolve address of overloaded function";
5026 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005028 case SK_CastDerivedToBaseRValue:
5029 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5030 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005031
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005032 case SK_CastDerivedToBaseXValue:
5033 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5034 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005036 case SK_CastDerivedToBaseLValue:
5037 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5038 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005040 case SK_BindReference:
5041 OS << "bind reference to lvalue";
5042 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005044 case SK_BindReferenceToTemporary:
5045 OS << "bind reference to a temporary";
5046 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005048 case SK_ExtraneousCopyToTemporary:
5049 OS << "extraneous C++03 copy to temporary";
5050 break;
5051
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005052 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005053 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005054 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005055
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005056 case SK_QualificationConversionRValue:
5057 OS << "qualification conversion (rvalue)";
5058
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005059 case SK_QualificationConversionXValue:
5060 OS << "qualification conversion (xvalue)";
5061
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005062 case SK_QualificationConversionLValue:
5063 OS << "qualification conversion (lvalue)";
5064 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005066 case SK_ConversionSequence:
5067 OS << "implicit conversion sequence (";
5068 S->ICS->DebugPrint(); // FIXME: use OS
5069 OS << ")";
5070 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005072 case SK_ListInitialization:
5073 OS << "list initialization";
5074 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005076 case SK_ConstructorInitialization:
5077 OS << "constructor initialization";
5078 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005080 case SK_ZeroInitialization:
5081 OS << "zero initialization";
5082 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005084 case SK_CAssignment:
5085 OS << "C assignment";
5086 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005088 case SK_StringInit:
5089 OS << "string initialization";
5090 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005091
5092 case SK_ObjCObjectConversion:
5093 OS << "Objective-C object conversion";
5094 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005095
5096 case SK_ArrayInit:
5097 OS << "array initialization";
5098 break;
John McCall31168b02011-06-15 23:02:42 +00005099
5100 case SK_PassByIndirectCopyRestore:
5101 OS << "pass by indirect copy and restore";
5102 break;
5103
5104 case SK_PassByIndirectRestore:
5105 OS << "pass by indirect restore";
5106 break;
5107
5108 case SK_ProduceObjCObject:
5109 OS << "Objective-C object retension";
5110 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005111 }
5112 }
5113}
5114
5115void InitializationSequence::dump() const {
5116 dump(llvm::errs());
5117}
5118
Douglas Gregore1314a62009-12-18 05:02:21 +00005119//===----------------------------------------------------------------------===//
5120// Initialization helper functions
5121//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005122bool
5123Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5124 ExprResult Init) {
5125 if (Init.isInvalid())
5126 return false;
5127
5128 Expr *InitE = Init.get();
5129 assert(InitE && "No initialization expression");
5130
5131 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5132 SourceLocation());
5133 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005134 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005135}
5136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005138Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5139 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00005140 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005141 if (Init.isInvalid())
5142 return ExprError();
5143
John McCall1f425642010-11-11 03:21:53 +00005144 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005145 assert(InitE && "No initialization expression?");
5146
5147 if (EqualLoc.isInvalid())
5148 EqualLoc = InitE->getLocStart();
5149
5150 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5151 EqualLoc);
5152 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5153 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00005154 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005155}