blob: 1d0575cd1c12582e7c866a12729c6613e09e66e8 [file] [log] [blame]
Steve Naroff0cca7492008-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//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000022#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattner79e079d2009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman8718a6a2009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner8879e3b2009-02-26 23:26:43 +000045 // Handle @encode, which is a narrow string.
46 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 return Init;
48
49 // Otherwise we can only handle string literals.
50 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000054 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000058
Eli Friedmanbb6415c2009-05-31 10:54:53 +000059 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60 // correction from DR343): "An array with element type compatible with a
61 // qualified or unqualified version of wchar_t may be initialized by a wide
62 // string literal, optionally enclosed in braces."
63 if (Context.typesAreCompatible(Context.getWCharType(),
64 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000065 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattnerdd8e0062009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattner79e079d2009-02-24 23:10:27 +000070static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71 // Get the length of the string as parsed.
72 uint64_t StrLength =
73 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner79e079d2009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000086 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000087 }
Mike Stump1eb44332009-09-09 15:08:12 +000088
Eli Friedman8718a6a2009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Eli Friedman8718a6a2009-05-29 18:22:49 +000091 // C99 6.7.8p14. We have an array of character type with known size. However,
92 // the size may be smaller or larger than the string we are initializing.
93 // FIXME: Avoid truncation for 64-bit length strings.
94 if (StrLength-1 > CAT->getSize().getZExtValue())
95 S.Diag(Str->getSourceRange().getBegin(),
96 diag::warn_initializer_string_for_char_array_too_long)
97 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000098
Eli Friedman8718a6a2009-05-29 18:22:49 +000099 // Set the type to the actual size that we are initializing. If we have
100 // something like:
101 // char x[1] = "foo";
102 // then this will set the string literal's type to char[1].
103 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000104}
105
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregor9e80f722009-01-29 01:05:33 +0000110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000137namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205 QualType CurrentObjectType,
206 InitListExpr *StructuredList,
207 unsigned StructuredIndex,
208 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000214
Douglas Gregord6d37de2009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000223 bool HadError() { return hadError; }
224
225 // @brief Retrieves the fully-structured initializer list used for
226 // semantic analysis and code generation.
227 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
Chris Lattner8b419b92009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000230
Douglas Gregord6d37de2009-12-22 00:05:34 +0000231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232 const InitializedEntity &ParentEntity,
233 InitListExpr *ILE,
234 bool &RequiresSecondPass) {
235 SourceLocation Loc = ILE->getSourceRange().getBegin();
236 unsigned NumInits = ILE->getNumInits();
237 InitializedEntity MemberEntity
238 = InitializedEntity::InitializeMember(Field, &ParentEntity);
239 if (Init >= NumInits || !ILE->getInit(Init)) {
240 // FIXME: We probably don't need to handle references
241 // specially here, since value-initialization of references is
242 // handled in InitializationSequence.
243 if (Field->getType()->isReferenceType()) {
244 // C++ [dcl.init.aggr]p9:
245 // If an incomplete or empty initializer-list leaves a
246 // member of reference type uninitialized, the program is
247 // ill-formed.
248 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249 << Field->getType()
250 << ILE->getSyntacticForm()->getSourceRange();
251 SemaRef.Diag(Field->getLocation(),
252 diag::note_uninit_reference_member);
253 hadError = true;
254 return;
255 }
256
257 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258 true);
259 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260 if (!InitSeq) {
261 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262 hadError = true;
263 return;
264 }
265
266 Sema::OwningExprResult MemberInit
267 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268 Sema::MultiExprArg(SemaRef, 0, 0));
269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenekba7bc552010-02-19 01:50:18 +0000284 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor4c678342009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Ted Kremenek6217b802009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000319
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000325 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000336 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000354 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000357
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssond3d824d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000376 Sema::OwningExprResult ElementInit
377 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378 Sema::MultiExprArg(SemaRef, 0, 0));
379 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381 return;
382 }
383
384 if (hadError) {
385 // Do nothing
386 } else if (Init < NumInits) {
387 ILE->setInit(Init, ElementInit.takeAs<Expr>());
388 } else if (InitSeq.getKind()
389 == InitializationSequence::ConstructorInitialization) {
390 // Value-initialization requires a constructor call, so
391 // extend the initializer list to include the constructor
392 // call and make a note that we'll need to take another pass
393 // through the initializer list.
Ted Kremenekba7bc552010-02-19 01:50:18 +0000394 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattner68355a52009-01-29 05:10:57 +0000403
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000408
Eli Friedmanb85f7072008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000416
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000431 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432 }
433 return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000449}
450
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
461 else if (T->isStructureType() || T->isUnionType())
462 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000467
Eli Friedman402256f2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000471 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000483
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregored8a93d2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000507 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
508 "{")
509 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000510 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000511 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000512 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000513}
514
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000515void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000516 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 unsigned &Index,
518 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000519 unsigned &StructuredIndex,
520 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 SyntacticToSemantic[IList] = StructuredList;
523 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000524 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
525 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor2c792812010-02-09 00:50:06 +0000526 IList->setType(T.getNonReferenceType());
527 StructuredList->setType(T.getNonReferenceType());
Eli Friedman638e1442008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530
Eli Friedman638e1442008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000540 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman08634522009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000563
Chris Lattner08202542009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000566 }
567 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000568
Eli Friedman759f2522009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000574}
575
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000600 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000604 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000627 } else {
628 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000629 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000630 assert(0 && "Unsupported initializer type");
631 }
632}
633
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000634void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000635 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000636 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000637 unsigned &Index,
638 InitListExpr *StructuredList,
639 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000640 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000641 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
642 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000643 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000644 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000645 = getStructuredSubobjectInit(IList, Index, ElemType,
646 StructuredList, StructuredIndex,
647 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000648 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 newStructuredList, newStructuredIndex);
650 ++StructuredIndex;
651 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000652 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
653 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000654 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000655 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000656 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000657 CheckScalarType(Entity, IList, ElemType, Index,
658 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000659 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000660 CheckReferenceType(Entity, IList, ElemType, Index,
661 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000662 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000663 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000664 // C++ [dcl.init.aggr]p12:
665 // All implicit type conversions (clause 4) are considered when
666 // initializing the aggregate member with an ini- tializer from
667 // an initializer-list. If the initializer can initialize a
668 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000669
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000670 // FIXME: Better EqualLoc?
671 InitializationKind Kind =
672 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
673 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
674
675 if (Seq) {
676 Sema::OwningExprResult Result =
677 Seq.Perform(SemaRef, Entity, Kind,
678 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
679 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000680 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000681
682 UpdateStructuredListElement(StructuredList, StructuredIndex,
683 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000684 ++Index;
685 return;
686 }
687
688 // Fall through for subaggregate initialization
689 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000690 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000691 //
692 // The initializer for a structure or union object that has
693 // automatic storage duration shall be either an initializer
694 // list as described below, or a single expression that has
695 // compatible structure or union type. In the latter case, the
696 // initial value of the object, including unnamed members, is
697 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000698 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000699 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000700 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
701 ++Index;
702 return;
703 }
704
705 // Fall through for subaggregate initialization
706 }
707
708 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000709 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000710 // [...] Otherwise, if the member is itself a non-empty
711 // subaggregate, brace elision is assumed and the initializer is
712 // considered for the initialization of the first member of
713 // the subaggregate.
714 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000715 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000716 StructuredIndex);
717 ++StructuredIndex;
718 } else {
719 // We cannot initialize this element, so let
720 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000721 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
722 SemaRef.Owned(expr));
723 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000724 hadError = true;
725 ++Index;
726 ++StructuredIndex;
727 }
728 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000729}
730
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000731void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000732 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000733 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000734 InitListExpr *StructuredList,
735 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000736 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000737 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000738 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000739 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000740 diag::err_many_braces_around_scalar_init)
741 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000742 hadError = true;
743 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000744 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000745 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000746 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000747 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000748 diag::err_designator_for_scalar_init)
749 << DeclType << expr->getSourceRange();
750 hadError = true;
751 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000752 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000753 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000754 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000755
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000756 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000757 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
758 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000759
Chandler Carruthb5719242010-02-13 07:23:01 +0000760 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000761
762 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000763 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000764 else {
765 ResultExpr = Result.takeAs<Expr>();
766
767 if (ResultExpr != expr) {
768 // The type was promoted, update initializer list.
769 IList->setInit(Index, ResultExpr);
770 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000771 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000772 if (hadError)
773 ++StructuredIndex;
774 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000775 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000776 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000777 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000778 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000779 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000780 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000781 ++Index;
782 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000783 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000784 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000785}
786
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000787void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
788 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000789 unsigned &Index,
790 InitListExpr *StructuredList,
791 unsigned &StructuredIndex) {
792 if (Index < IList->getNumInits()) {
793 Expr *expr = IList->getInit(Index);
794 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000795 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000796 << DeclType << IList->getSourceRange();
797 hadError = true;
798 ++Index;
799 ++StructuredIndex;
800 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000801 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000802
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000803 Sema::OwningExprResult Result =
804 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
805 SemaRef.Owned(expr));
806
807 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000808 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000809
810 expr = Result.takeAs<Expr>();
811 IList->setInit(Index, expr);
812
Douglas Gregor930d8b52009-01-30 22:09:00 +0000813 if (hadError)
814 ++StructuredIndex;
815 else
816 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
817 ++Index;
818 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000819 // FIXME: It would be wonderful if we could point at the actual member. In
820 // general, it would be useful to pass location information down the stack,
821 // so that we know the location (or decl) of the "current object" being
822 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000823 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000824 diag::err_init_reference_member_uninitialized)
825 << DeclType
826 << IList->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832}
833
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000834void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000835 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000836 unsigned &Index,
837 InitListExpr *StructuredList,
838 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000839 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000840 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000841 unsigned maxElements = VT->getNumElements();
842 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000843 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Nate Begeman2ef13e52009-08-10 23:49:36 +0000845 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000846 InitializedEntity ElementEntity =
847 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000848
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000849 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
850 // Don't attempt to go past the end of the init list
851 if (Index >= IList->getNumInits())
852 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000853
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000854 ElementEntity.setElementIndex(Index);
855 CheckSubElementType(ElementEntity, IList, elementType, Index,
856 StructuredList, StructuredIndex);
857 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000858 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000859 InitializedEntity ElementEntity =
860 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
861
Nate Begeman2ef13e52009-08-10 23:49:36 +0000862 // OpenCL initializers allows vectors to be constructed from vectors.
863 for (unsigned i = 0; i < maxElements; ++i) {
864 // Don't attempt to go past the end of the init list
865 if (Index >= IList->getNumInits())
866 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000867
868 ElementEntity.setElementIndex(Index);
869
Nate Begeman2ef13e52009-08-10 23:49:36 +0000870 QualType IType = IList->getInit(Index)->getType();
871 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000872 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000873 StructuredList, StructuredIndex);
874 ++numEltsInit;
875 } else {
John McCall183700f2009-09-21 23:43:11 +0000876 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000877 unsigned numIElts = IVT->getNumElements();
878 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
879 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000880 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000881 StructuredList, StructuredIndex);
882 numEltsInit += numIElts;
883 }
884 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Nate Begeman2ef13e52009-08-10 23:49:36 +0000887 // OpenCL & AltiVec require all elements to be initialized.
888 if (numEltsInit != maxElements)
889 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
890 SemaRef.Diag(IList->getSourceRange().getBegin(),
891 diag::err_vector_incorrect_num_initializers)
892 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000893 }
894}
895
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000896void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000897 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000898 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000900 unsigned &Index,
901 InitListExpr *StructuredList,
902 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000903 // Check for the special-case of initializing an array with a string.
904 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000905 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
906 SemaRef.Context)) {
907 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000908 // We place the string literal directly into the resulting
909 // initializer list. This is the only place where the structure
910 // of the structured initializer list doesn't match exactly,
911 // because doing so would involve allocating one character
912 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000913 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000914 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000915 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000916 return;
917 }
918 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000919 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000920 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000921 // Check for VLAs; in standard C it would be possible to check this
922 // earlier, but I don't know where clang accepts VLAs (gcc accepts
923 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000924 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000925 diag::err_variable_object_no_init)
926 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000927 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000928 ++Index;
929 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000930 return;
931 }
932
Douglas Gregor05c13a32009-01-22 00:58:24 +0000933 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000934 llvm::APSInt maxElements(elementIndex.getBitWidth(),
935 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000936 bool maxElementsKnown = false;
937 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000938 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000939 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000940 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000941 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000942 maxElementsKnown = true;
943 }
944
Chris Lattner08202542009-02-24 22:50:46 +0000945 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000946 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000947 while (Index < IList->getNumInits()) {
948 Expr *Init = IList->getInit(Index);
949 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000950 // If we're not the subobject that matches up with the '{' for
951 // the designator, we shouldn't be handling the
952 // designator. Return immediately.
953 if (!SubobjectIsDesignatorContext)
954 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000955
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000956 // Handle this designated initializer. elementIndex will be
957 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000958 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000959 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000960 StructuredList, StructuredIndex, true,
961 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000962 hadError = true;
963 continue;
964 }
965
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000966 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
967 maxElements.extend(elementIndex.getBitWidth());
968 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
969 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000970 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000971
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000972 // If the array is of incomplete type, keep track of the number of
973 // elements in the initializer.
974 if (!maxElementsKnown && elementIndex > maxElements)
975 maxElements = elementIndex;
976
Douglas Gregor05c13a32009-01-22 00:58:24 +0000977 continue;
978 }
979
980 // If we know the maximum number of elements, and we've already
981 // hit it, stop consuming elements in the initializer list.
982 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000983 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000984
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000985 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000986 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000987 Entity);
988 // Check this element.
989 CheckSubElementType(ElementEntity, IList, elementType, Index,
990 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000991 ++elementIndex;
992
993 // If the array is of incomplete type, keep track of the number of
994 // elements in the initializer.
995 if (!maxElementsKnown && elementIndex > maxElements)
996 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000997 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000998 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000999 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001000 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001001 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001002 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001003 // Sizing an array implicitly to zero is not allowed by ISO C,
1004 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001005 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001006 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001007 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001008
Mike Stump1eb44332009-09-09 15:08:12 +00001009 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001010 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001011 }
1012}
1013
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001014void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001015 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001016 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001017 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001018 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001019 unsigned &Index,
1020 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001021 unsigned &StructuredIndex,
1022 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001023 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Eli Friedmanb85f7072008-05-19 19:16:24 +00001025 // If the record is invalid, some of it's members are invalid. To avoid
1026 // confusion, we forgo checking the intializer for the entire record.
1027 if (structDecl->isInvalidDecl()) {
1028 hadError = true;
1029 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001030 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001031
1032 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1033 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001034 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001035 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001036 Field != FieldEnd; ++Field) {
1037 if (Field->getDeclName()) {
1038 StructuredList->setInitializedFieldInUnion(*Field);
1039 break;
1040 }
1041 }
1042 return;
1043 }
1044
Douglas Gregor05c13a32009-01-22 00:58:24 +00001045 // If structDecl is a forward declaration, this loop won't do
1046 // anything except look at designated initializers; That's okay,
1047 // because an error should get printed out elsewhere. It might be
1048 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001049 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001050 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001051 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001052 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001053 while (Index < IList->getNumInits()) {
1054 Expr *Init = IList->getInit(Index);
1055
1056 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001057 // If we're not the subobject that matches up with the '{' for
1058 // the designator, we shouldn't be handling the
1059 // designator. Return immediately.
1060 if (!SubobjectIsDesignatorContext)
1061 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001062
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001063 // Handle this designated initializer. Field will be updated to
1064 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001065 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001066 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001067 StructuredList, StructuredIndex,
1068 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001069 hadError = true;
1070
Douglas Gregordfb5e592009-02-12 19:00:39 +00001071 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001072
1073 // Disable check for missing fields when designators are used.
1074 // This matches gcc behaviour.
1075 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001076 continue;
1077 }
1078
1079 if (Field == FieldEnd) {
1080 // We've run out of fields. We're done.
1081 break;
1082 }
1083
Douglas Gregordfb5e592009-02-12 19:00:39 +00001084 // We've already initialized a member of a union. We're done.
1085 if (InitializedSomething && DeclType->isUnionType())
1086 break;
1087
Douglas Gregor44b43212008-12-11 16:49:14 +00001088 // If we've hit the flexible array member at the end, we're done.
1089 if (Field->getType()->isIncompleteArrayType())
1090 break;
1091
Douglas Gregor0bb76892009-01-29 16:53:55 +00001092 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001093 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001094 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001095 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001096 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001097
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001098 InitializedEntity MemberEntity =
1099 InitializedEntity::InitializeMember(*Field, &Entity);
1100 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1101 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001102 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001103
1104 if (DeclType->isUnionType()) {
1105 // Initialize the first field within the union.
1106 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001107 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001108
1109 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001110 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001111
John McCall80639de2010-03-11 19:32:38 +00001112 // Emit warnings for missing struct field initializers.
1113 if (CheckForMissingFields && Field != FieldEnd &&
1114 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1115 // It is possible we have one or more unnamed bitfields remaining.
1116 // Find first (if any) named field and emit warning.
1117 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1118 it != end; ++it) {
1119 if (!it->isUnnamedBitfield()) {
1120 SemaRef.Diag(IList->getSourceRange().getEnd(),
1121 diag::warn_missing_field_initializers) << it->getName();
1122 break;
1123 }
1124 }
1125 }
1126
Mike Stump1eb44332009-09-09 15:08:12 +00001127 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001128 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001129 return;
1130
1131 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001133 (!isa<InitListExpr>(IList->getInit(Index)) ||
1134 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001135 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001136 diag::err_flexible_array_init_nonempty)
1137 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001138 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001139 << *Field;
1140 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001141 ++Index;
1142 return;
1143 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001144 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001145 diag::ext_flexible_array_init)
1146 << IList->getInit(Index)->getSourceRange().getBegin();
1147 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1148 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001149 }
1150
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001151 InitializedEntity MemberEntity =
1152 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001153
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001154 if (isa<InitListExpr>(IList->getInit(Index)))
1155 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1156 StructuredList, StructuredIndex);
1157 else
1158 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001159 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001160}
Steve Naroff0cca7492008-05-01 22:18:59 +00001161
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001162/// \brief Expand a field designator that refers to a member of an
1163/// anonymous struct or union into a series of field designators that
1164/// refers to the field within the appropriate subobject.
1165///
1166/// Field/FieldIndex will be updated to point to the (new)
1167/// currently-designated field.
1168static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001169 DesignatedInitExpr *DIE,
1170 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001171 FieldDecl *Field,
1172 RecordDecl::field_iterator &FieldIter,
1173 unsigned &FieldIndex) {
1174 typedef DesignatedInitExpr::Designator Designator;
1175
1176 // Build the path from the current object to the member of the
1177 // anonymous struct/union (backwards).
1178 llvm::SmallVector<FieldDecl *, 4> Path;
1179 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001181 // Build the replacement designators.
1182 llvm::SmallVector<Designator, 4> Replacements;
1183 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1184 FI = Path.rbegin(), FIEnd = Path.rend();
1185 FI != FIEnd; ++FI) {
1186 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001187 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001188 DIE->getDesignator(DesigIdx)->getDotLoc(),
1189 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1190 else
1191 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1192 SourceLocation()));
1193 Replacements.back().setField(*FI);
1194 }
1195
1196 // Expand the current designator into the set of replacement
1197 // designators, so we have a full subobject path down to where the
1198 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001199 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001200 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001202 // Update FieldIter/FieldIndex;
1203 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001204 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001205 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001206 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001207 FieldIter != FEnd; ++FieldIter) {
1208 if (FieldIter->isUnnamedBitfield())
1209 continue;
1210
1211 if (*FieldIter == Path.back())
1212 return;
1213
1214 ++FieldIndex;
1215 }
1216
1217 assert(false && "Unable to find anonymous struct/union field");
1218}
1219
Douglas Gregor05c13a32009-01-22 00:58:24 +00001220/// @brief Check the well-formedness of a C99 designated initializer.
1221///
1222/// Determines whether the designated initializer @p DIE, which
1223/// resides at the given @p Index within the initializer list @p
1224/// IList, is well-formed for a current object of type @p DeclType
1225/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001226/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001227/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001228///
1229/// @param IList The initializer list in which this designated
1230/// initializer occurs.
1231///
Douglas Gregor71199712009-04-15 04:56:10 +00001232/// @param DIE The designated initializer expression.
1233///
1234/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001235///
1236/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1237/// into which the designation in @p DIE should refer.
1238///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001239/// @param NextField If non-NULL and the first designator in @p DIE is
1240/// a field, this will be set to the field declaration corresponding
1241/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001242///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001243/// @param NextElementIndex If non-NULL and the first designator in @p
1244/// DIE is an array designator or GNU array-range designator, this
1245/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246///
1247/// @param Index Index into @p IList where the designated initializer
1248/// @p DIE occurs.
1249///
Douglas Gregor4c678342009-01-28 21:54:33 +00001250/// @param StructuredList The initializer list expression that
1251/// describes all of the subobject initializers in the order they'll
1252/// actually be initialized.
1253///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001254/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001255bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001256InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001257 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001258 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001259 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001260 QualType &CurrentObjectType,
1261 RecordDecl::field_iterator *NextField,
1262 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001263 unsigned &Index,
1264 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001265 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001266 bool FinishSubobjectInit,
1267 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001268 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001269 // Check the actual initialization for the designated object type.
1270 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001271
1272 // Temporarily remove the designator expression from the
1273 // initializer list that the child calls see, so that we don't try
1274 // to re-process the designator.
1275 unsigned OldIndex = Index;
1276 IList->setInit(OldIndex, DIE->getInit());
1277
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001278 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001279 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001280
1281 // Restore the designated initializer expression in the syntactic
1282 // form of the initializer list.
1283 if (IList->getInit(OldIndex) != DIE->getInit())
1284 DIE->setInit(IList->getInit(OldIndex));
1285 IList->setInit(OldIndex, DIE);
1286
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001287 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001288 }
1289
Douglas Gregor71199712009-04-15 04:56:10 +00001290 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001291 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001292 "Need a non-designated initializer list to start from");
1293
Douglas Gregor71199712009-04-15 04:56:10 +00001294 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001295 // Determine the structural initializer list that corresponds to the
1296 // current subobject.
1297 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001298 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001299 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001300 SourceRange(D->getStartLocation(),
1301 DIE->getSourceRange().getEnd()));
1302 assert(StructuredList && "Expected a structured initializer list");
1303
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001304 if (D->isFieldDesignator()) {
1305 // C99 6.7.8p7:
1306 //
1307 // If a designator has the form
1308 //
1309 // . identifier
1310 //
1311 // then the current object (defined below) shall have
1312 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001313 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001314 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001315 if (!RT) {
1316 SourceLocation Loc = D->getDotLoc();
1317 if (Loc.isInvalid())
1318 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001319 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1320 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001321 ++Index;
1322 return true;
1323 }
1324
Douglas Gregor4c678342009-01-28 21:54:33 +00001325 // Note: we perform a linear search of the fields here, despite
1326 // the fact that we have a faster lookup method, because we always
1327 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001328 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001329 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001330 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001331 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001332 Field = RT->getDecl()->field_begin(),
1333 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001334 for (; Field != FieldEnd; ++Field) {
1335 if (Field->isUnnamedBitfield())
1336 continue;
1337
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001338 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001339 break;
1340
1341 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001342 }
1343
Douglas Gregor4c678342009-01-28 21:54:33 +00001344 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001345 // There was no normal field in the struct with the designated
1346 // name. Perform another lookup for this name, which may find
1347 // something that we can't designate (e.g., a member function),
1348 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001349 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001350 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001351 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001352 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001353 // Name lookup didn't find anything. Determine whether this
1354 // was a typo for another field name.
1355 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1356 Sema::LookupMemberName);
1357 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1358 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1359 ReplacementField->getDeclContext()->getLookupContext()
1360 ->Equals(RT->getDecl())) {
1361 SemaRef.Diag(D->getFieldLoc(),
1362 diag::err_field_designator_unknown_suggest)
1363 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001364 << FixItHint::CreateReplacement(D->getFieldLoc(),
1365 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001366 SemaRef.Diag(ReplacementField->getLocation(),
1367 diag::note_previous_decl)
1368 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001369 } else {
1370 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1371 << FieldName << CurrentObjectType;
1372 ++Index;
1373 return true;
1374 }
1375 } else if (!KnownField) {
1376 // Determine whether we found a field at all.
1377 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1378 }
1379
1380 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001382 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001383 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001384 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001385 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001386 ++Index;
1387 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001388 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001389
1390 if (!KnownField &&
1391 cast<RecordDecl>((ReplacementField)->getDeclContext())
1392 ->isAnonymousStructOrUnion()) {
1393 // Handle an field designator that refers to a member of an
1394 // anonymous struct or union.
1395 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1396 ReplacementField,
1397 Field, FieldIndex);
1398 D = DIE->getDesignator(DesigIdx);
1399 } else if (!KnownField) {
1400 // The replacement field comes from typo correction; find it
1401 // in the list of fields.
1402 FieldIndex = 0;
1403 Field = RT->getDecl()->field_begin();
1404 for (; Field != FieldEnd; ++Field) {
1405 if (Field->isUnnamedBitfield())
1406 continue;
1407
1408 if (ReplacementField == *Field ||
1409 Field->getIdentifier() == ReplacementField->getIdentifier())
1410 break;
1411
1412 ++FieldIndex;
1413 }
1414 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001415 } else if (!KnownField &&
1416 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001417 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001418 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1419 Field, FieldIndex);
1420 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001421 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001422
1423 // All of the fields of a union are located at the same place in
1424 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001425 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001426 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001427 StructuredList->setInitializedFieldInUnion(*Field);
1428 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001429
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001430 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001431 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Douglas Gregor4c678342009-01-28 21:54:33 +00001433 // Make sure that our non-designated initializer list has space
1434 // for a subobject corresponding to this field.
1435 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001436 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001437
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001438 // This designator names a flexible array member.
1439 if (Field->getType()->isIncompleteArrayType()) {
1440 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001441 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001442 // We can't designate an object within the flexible array
1443 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001444 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001445 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001446 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001447 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001448 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001449 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001450 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001451 << *Field;
1452 Invalid = true;
1453 }
1454
1455 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1456 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001457 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 diag::err_flexible_array_init_needs_braces)
1459 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001460 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001461 << *Field;
1462 Invalid = true;
1463 }
1464
1465 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001466 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001467 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001468 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001469 diag::err_flexible_array_init_nonempty)
1470 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001471 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 << *Field;
1473 Invalid = true;
1474 }
1475
1476 if (Invalid) {
1477 ++Index;
1478 return true;
1479 }
1480
1481 // Initialize the array.
1482 bool prevHadError = hadError;
1483 unsigned newStructuredIndex = FieldIndex;
1484 unsigned OldIndex = Index;
1485 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001486
1487 InitializedEntity MemberEntity =
1488 InitializedEntity::InitializeMember(*Field, &Entity);
1489 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001490 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001491
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001492 IList->setInit(OldIndex, DIE);
1493 if (hadError && !prevHadError) {
1494 ++Field;
1495 ++FieldIndex;
1496 if (NextField)
1497 *NextField = Field;
1498 StructuredIndex = FieldIndex;
1499 return true;
1500 }
1501 } else {
1502 // Recurse to check later designated subobjects.
1503 QualType FieldType = (*Field)->getType();
1504 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001505
1506 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001507 InitializedEntity::InitializeMember(*Field, &Entity);
1508 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001509 FieldType, 0, 0, Index,
1510 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001511 true, false))
1512 return true;
1513 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001514
1515 // Find the position of the next field to be initialized in this
1516 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001517 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001518 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001519
1520 // If this the first designator, our caller will continue checking
1521 // the rest of this struct/class/union subobject.
1522 if (IsFirstDesignator) {
1523 if (NextField)
1524 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001525 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001526 return false;
1527 }
1528
Douglas Gregor34e79462009-01-28 23:36:17 +00001529 if (!FinishSubobjectInit)
1530 return false;
1531
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001532 // We've already initialized something in the union; we're done.
1533 if (RT->getDecl()->isUnion())
1534 return hadError;
1535
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001536 // Check the remaining fields within this class/struct/union subobject.
1537 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001538
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001539 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001540 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 return hadError && !prevHadError;
1542 }
1543
1544 // C99 6.7.8p6:
1545 //
1546 // If a designator has the form
1547 //
1548 // [ constant-expression ]
1549 //
1550 // then the current object (defined below) shall have array
1551 // type and the expression shall be an integer constant
1552 // expression. If the array is of unknown size, any
1553 // nonnegative value is valid.
1554 //
1555 // Additionally, cope with the GNU extension that permits
1556 // designators of the form
1557 //
1558 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001559 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001560 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001561 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 << CurrentObjectType;
1563 ++Index;
1564 return true;
1565 }
1566
1567 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1569 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001570 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001571 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001572 DesignatedEndIndex = DesignatedStartIndex;
1573 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001575
Mike Stump1eb44332009-09-09 15:08:12 +00001576
1577 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001578 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001579 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001580 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001582
Chris Lattner3bf68932009-04-25 21:59:05 +00001583 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001584 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001585 }
1586
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587 if (isa<ConstantArrayType>(AT)) {
1588 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001589 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1590 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1591 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1592 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1593 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001594 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001595 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001596 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 << IndexExpr->getSourceRange();
1598 ++Index;
1599 return true;
1600 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001601 } else {
1602 // Make sure the bit-widths and signedness match.
1603 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1604 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001605 else if (DesignatedStartIndex.getBitWidth() <
1606 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001607 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1608 DesignatedStartIndex.setIsUnsigned(true);
1609 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Douglas Gregor4c678342009-01-28 21:54:33 +00001612 // Make sure that our non-designated initializer list has space
1613 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001614 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001615 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001616 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001617
Douglas Gregor34e79462009-01-28 23:36:17 +00001618 // Repeatedly perform subobject initializations in the range
1619 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001620
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 // Move to the next designator
1622 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1623 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001624
1625 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001626 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001627
Douglas Gregor34e79462009-01-28 23:36:17 +00001628 while (DesignatedStartIndex <= DesignatedEndIndex) {
1629 // Recurse to check later designated subobjects.
1630 QualType ElementType = AT->getElementType();
1631 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001632
1633 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001634 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001635 ElementType, 0, 0, Index,
1636 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001637 (DesignatedStartIndex == DesignatedEndIndex),
1638 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001639 return true;
1640
1641 // Move to the next index in the array that we'll be initializing.
1642 ++DesignatedStartIndex;
1643 ElementIndex = DesignatedStartIndex.getZExtValue();
1644 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001645
1646 // If this the first designator, our caller will continue checking
1647 // the rest of this array subobject.
1648 if (IsFirstDesignator) {
1649 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001650 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001651 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001652 return false;
1653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 if (!FinishSubobjectInit)
1656 return false;
1657
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001658 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001659 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001660 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001661 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001662 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001663 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001664}
1665
Douglas Gregor4c678342009-01-28 21:54:33 +00001666// Get the structured initializer list for a subobject of type
1667// @p CurrentObjectType.
1668InitListExpr *
1669InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1670 QualType CurrentObjectType,
1671 InitListExpr *StructuredList,
1672 unsigned StructuredIndex,
1673 SourceRange InitRange) {
1674 Expr *ExistingInit = 0;
1675 if (!StructuredList)
1676 ExistingInit = SyntacticToSemantic[IList];
1677 else if (StructuredIndex < StructuredList->getNumInits())
1678 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Douglas Gregor4c678342009-01-28 21:54:33 +00001680 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1681 return Result;
1682
1683 if (ExistingInit) {
1684 // We are creating an initializer list that initializes the
1685 // subobjects of the current object, but there was already an
1686 // initialization that completely initialized the current
1687 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001688 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 // struct X { int a, b; };
1690 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001691 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001692 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1693 // designated initializer re-initializes the whole
1694 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001695 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001696 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001697 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001698 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001699 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001700 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001701 << ExistingInit->getSourceRange();
1702 }
1703
Mike Stump1eb44332009-09-09 15:08:12 +00001704 InitListExpr *Result
Ted Kremenekba7bc552010-02-19 01:50:18 +00001705 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1706 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001707
Douglas Gregor2c792812010-02-09 00:50:06 +00001708 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001709
Douglas Gregorfa219202009-03-20 23:58:33 +00001710 // Pre-allocate storage for the structured initializer list.
1711 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001712 unsigned NumInits = 0;
1713 if (!StructuredList)
1714 NumInits = IList->getNumInits();
1715 else if (Index < IList->getNumInits()) {
1716 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1717 NumInits = SubList->getNumInits();
1718 }
1719
Mike Stump1eb44332009-09-09 15:08:12 +00001720 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001721 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1722 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1723 NumElements = CAType->getSize().getZExtValue();
1724 // Simple heuristic so that we don't allocate a very large
1725 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001726 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001727 NumElements = 0;
1728 }
John McCall183700f2009-09-21 23:43:11 +00001729 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001730 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001731 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001732 RecordDecl *RDecl = RType->getDecl();
1733 if (RDecl->isUnion())
1734 NumElements = 1;
1735 else
Mike Stump1eb44332009-09-09 15:08:12 +00001736 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001737 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001738 }
1739
Douglas Gregor08457732009-03-21 18:13:52 +00001740 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001741 NumElements = IList->getNumInits();
1742
Ted Kremenekba7bc552010-02-19 01:50:18 +00001743 Result->reserveInits(NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001744
Douglas Gregor4c678342009-01-28 21:54:33 +00001745 // Link this new initializer list into the structured initializer
1746 // lists.
1747 if (StructuredList)
Ted Kremenekba7bc552010-02-19 01:50:18 +00001748 StructuredList->updateInit(StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001749 else {
1750 Result->setSyntacticForm(IList);
1751 SyntacticToSemantic[IList] = Result;
1752 }
1753
1754 return Result;
1755}
1756
1757/// Update the initializer at index @p StructuredIndex within the
1758/// structured initializer list to the value @p expr.
1759void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1760 unsigned &StructuredIndex,
1761 Expr *expr) {
1762 // No structured initializer list to update
1763 if (!StructuredList)
1764 return;
1765
Ted Kremenekba7bc552010-02-19 01:50:18 +00001766 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001767 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001768 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 diag::warn_initializer_overrides)
1770 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001771 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001772 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001773 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 << PrevInit->getSourceRange();
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Douglas Gregor4c678342009-01-28 21:54:33 +00001777 ++StructuredIndex;
1778}
1779
Douglas Gregor05c13a32009-01-22 00:58:24 +00001780/// Check that the given Index expression is a valid array designator
1781/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001782/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001783/// and produces a reasonable diagnostic if there is a
1784/// failure. Returns true if there was an error, false otherwise. If
1785/// everything went okay, Value will receive the value of the constant
1786/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001787static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001788CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001789 SourceLocation Loc = Index->getSourceRange().getBegin();
1790
1791 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001792 if (S.VerifyIntegerConstantExpression(Index, &Value))
1793 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001794
Chris Lattner3bf68932009-04-25 21:59:05 +00001795 if (Value.isSigned() && Value.isNegative())
1796 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001797 << Value.toString(10) << Index->getSourceRange();
1798
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001799 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001800 return false;
1801}
1802
1803Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1804 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001805 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001806 OwningExprResult Init) {
1807 typedef DesignatedInitExpr::Designator ASTDesignator;
1808
1809 bool Invalid = false;
1810 llvm::SmallVector<ASTDesignator, 32> Designators;
1811 llvm::SmallVector<Expr *, 32> InitExpressions;
1812
1813 // Build designators and check array designator expressions.
1814 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1815 const Designator &D = Desig.getDesignator(Idx);
1816 switch (D.getKind()) {
1817 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001818 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001819 D.getFieldLoc()));
1820 break;
1821
1822 case Designator::ArrayDesignator: {
1823 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1824 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001825 if (!Index->isTypeDependent() &&
1826 !Index->isValueDependent() &&
1827 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001828 Invalid = true;
1829 else {
1830 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001831 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001832 D.getRBracketLoc()));
1833 InitExpressions.push_back(Index);
1834 }
1835 break;
1836 }
1837
1838 case Designator::ArrayRangeDesignator: {
1839 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1840 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1841 llvm::APSInt StartValue;
1842 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001843 bool StartDependent = StartIndex->isTypeDependent() ||
1844 StartIndex->isValueDependent();
1845 bool EndDependent = EndIndex->isTypeDependent() ||
1846 EndIndex->isValueDependent();
1847 if ((!StartDependent &&
1848 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1849 (!EndDependent &&
1850 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001851 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001852 else {
1853 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001854 if (StartDependent || EndDependent) {
1855 // Nothing to compute.
1856 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001857 EndValue.extend(StartValue.getBitWidth());
1858 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1859 StartValue.extend(EndValue.getBitWidth());
1860
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001861 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001862 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001863 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001864 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1865 Invalid = true;
1866 } else {
1867 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001868 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001869 D.getEllipsisLoc(),
1870 D.getRBracketLoc()));
1871 InitExpressions.push_back(StartIndex);
1872 InitExpressions.push_back(EndIndex);
1873 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001874 }
1875 break;
1876 }
1877 }
1878 }
1879
1880 if (Invalid || Init.isInvalid())
1881 return ExprError();
1882
1883 // Clear out the expressions within the designation.
1884 Desig.ClearExprs(*this);
1885
1886 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001887 = DesignatedInitExpr::Create(Context,
1888 Designators.data(), Designators.size(),
1889 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001890 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001891 return Owned(DIE);
1892}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001893
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001894bool Sema::CheckInitList(const InitializedEntity &Entity,
1895 InitListExpr *&InitList, QualType &DeclType) {
1896 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001897 if (!CheckInitList.HadError())
1898 InitList = CheckInitList.getFullyStructuredList();
1899
1900 return CheckInitList.HadError();
1901}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001902
Douglas Gregor20093b42009-12-09 23:02:17 +00001903//===----------------------------------------------------------------------===//
1904// Initialization entity
1905//===----------------------------------------------------------------------===//
1906
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001907InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1908 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001909 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001910{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001911 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1912 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001913 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001914 } else {
1915 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001916 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001917 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001918}
1919
1920InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1921 CXXBaseSpecifier *Base)
1922{
1923 InitializedEntity Result;
1924 Result.Kind = EK_Base;
1925 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001926 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001927 return Result;
1928}
1929
Douglas Gregor99a2e602009-12-16 01:38:02 +00001930DeclarationName InitializedEntity::getName() const {
1931 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001932 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001933 if (!VariableOrMember)
1934 return DeclarationName();
1935 // Fall through
1936
1937 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001938 case EK_Member:
1939 return VariableOrMember->getDeclName();
1940
1941 case EK_Result:
1942 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001943 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001944 case EK_Temporary:
1945 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001946 case EK_ArrayElement:
1947 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001948 return DeclarationName();
1949 }
1950
1951 // Silence GCC warning
1952 return DeclarationName();
1953}
1954
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001955DeclaratorDecl *InitializedEntity::getDecl() const {
1956 switch (getKind()) {
1957 case EK_Variable:
1958 case EK_Parameter:
1959 case EK_Member:
1960 return VariableOrMember;
1961
1962 case EK_Result:
1963 case EK_Exception:
1964 case EK_New:
1965 case EK_Temporary:
1966 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001967 case EK_ArrayElement:
1968 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001969 return 0;
1970 }
1971
1972 // Silence GCC warning
1973 return 0;
1974}
1975
Douglas Gregor20093b42009-12-09 23:02:17 +00001976//===----------------------------------------------------------------------===//
1977// Initialization sequence
1978//===----------------------------------------------------------------------===//
1979
1980void InitializationSequence::Step::Destroy() {
1981 switch (Kind) {
1982 case SK_ResolveAddressOfOverloadedFunction:
1983 case SK_CastDerivedToBaseRValue:
1984 case SK_CastDerivedToBaseLValue:
1985 case SK_BindReference:
1986 case SK_BindReferenceToTemporary:
1987 case SK_UserConversion:
1988 case SK_QualificationConversionRValue:
1989 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001990 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001991 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001992 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001993 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001994 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001995 break;
1996
1997 case SK_ConversionSequence:
1998 delete ICS;
1999 }
2000}
2001
Douglas Gregorb70cf442010-03-26 20:14:36 +00002002bool InitializationSequence::isDirectReferenceBinding() const {
2003 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2004}
2005
2006bool InitializationSequence::isAmbiguous() const {
2007 if (getKind() != FailedSequence)
2008 return false;
2009
2010 switch (getFailureKind()) {
2011 case FK_TooManyInitsForReference:
2012 case FK_ArrayNeedsInitList:
2013 case FK_ArrayNeedsInitListOrStringLiteral:
2014 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2015 case FK_NonConstLValueReferenceBindingToTemporary:
2016 case FK_NonConstLValueReferenceBindingToUnrelated:
2017 case FK_RValueReferenceBindingToLValue:
2018 case FK_ReferenceInitDropsQualifiers:
2019 case FK_ReferenceInitFailed:
2020 case FK_ConversionFailed:
2021 case FK_TooManyInitsForScalar:
2022 case FK_ReferenceBindingToInitList:
2023 case FK_InitListBadDestinationType:
2024 case FK_DefaultInitOfConst:
2025 return false;
2026
2027 case FK_ReferenceInitOverloadFailed:
2028 case FK_UserConversionOverloadFailed:
2029 case FK_ConstructorOverloadFailed:
2030 return FailedOverloadResult == OR_Ambiguous;
2031 }
2032
2033 return false;
2034}
2035
Douglas Gregor20093b42009-12-09 23:02:17 +00002036void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002037 FunctionDecl *Function,
2038 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002039 Step S;
2040 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2041 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002042 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002043 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002044 Steps.push_back(S);
2045}
2046
2047void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2048 bool IsLValue) {
2049 Step S;
2050 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2051 S.Type = BaseType;
2052 Steps.push_back(S);
2053}
2054
2055void InitializationSequence::AddReferenceBindingStep(QualType T,
2056 bool BindingTemporary) {
2057 Step S;
2058 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2059 S.Type = T;
2060 Steps.push_back(S);
2061}
2062
Eli Friedman03981012009-12-11 02:42:07 +00002063void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002064 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002065 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002066 Step S;
2067 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002068 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002069 S.Function.Function = Function;
2070 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002071 Steps.push_back(S);
2072}
2073
2074void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2075 bool IsLValue) {
2076 Step S;
2077 S.Kind = IsLValue? SK_QualificationConversionLValue
2078 : SK_QualificationConversionRValue;
2079 S.Type = Ty;
2080 Steps.push_back(S);
2081}
2082
2083void InitializationSequence::AddConversionSequenceStep(
2084 const ImplicitConversionSequence &ICS,
2085 QualType T) {
2086 Step S;
2087 S.Kind = SK_ConversionSequence;
2088 S.Type = T;
2089 S.ICS = new ImplicitConversionSequence(ICS);
2090 Steps.push_back(S);
2091}
2092
Douglas Gregord87b61f2009-12-10 17:56:55 +00002093void InitializationSequence::AddListInitializationStep(QualType T) {
2094 Step S;
2095 S.Kind = SK_ListInitialization;
2096 S.Type = T;
2097 Steps.push_back(S);
2098}
2099
Douglas Gregor51c56d62009-12-14 20:49:26 +00002100void
2101InitializationSequence::AddConstructorInitializationStep(
2102 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002103 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002104 QualType T) {
2105 Step S;
2106 S.Kind = SK_ConstructorInitialization;
2107 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002108 S.Function.Function = Constructor;
2109 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002110 Steps.push_back(S);
2111}
2112
Douglas Gregor71d17402009-12-15 00:01:57 +00002113void InitializationSequence::AddZeroInitializationStep(QualType T) {
2114 Step S;
2115 S.Kind = SK_ZeroInitialization;
2116 S.Type = T;
2117 Steps.push_back(S);
2118}
2119
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002120void InitializationSequence::AddCAssignmentStep(QualType T) {
2121 Step S;
2122 S.Kind = SK_CAssignment;
2123 S.Type = T;
2124 Steps.push_back(S);
2125}
2126
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002127void InitializationSequence::AddStringInitStep(QualType T) {
2128 Step S;
2129 S.Kind = SK_StringInit;
2130 S.Type = T;
2131 Steps.push_back(S);
2132}
2133
Douglas Gregor20093b42009-12-09 23:02:17 +00002134void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2135 OverloadingResult Result) {
2136 SequenceKind = FailedSequence;
2137 this->Failure = Failure;
2138 this->FailedOverloadResult = Result;
2139}
2140
2141//===----------------------------------------------------------------------===//
2142// Attempt initialization
2143//===----------------------------------------------------------------------===//
2144
2145/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002146static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002147 const InitializedEntity &Entity,
2148 const InitializationKind &Kind,
2149 InitListExpr *InitList,
2150 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002151 // FIXME: We only perform rudimentary checking of list
2152 // initializations at this point, then assume that any list
2153 // initialization of an array, aggregate, or scalar will be
2154 // well-formed. We we actually "perform" list initialization, we'll
2155 // do all of the necessary checking. C++0x initializer lists will
2156 // force us to perform more checking here.
2157 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2158
Douglas Gregord6542d82009-12-22 15:35:07 +00002159 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002160
2161 // C++ [dcl.init]p13:
2162 // If T is a scalar type, then a declaration of the form
2163 //
2164 // T x = { a };
2165 //
2166 // is equivalent to
2167 //
2168 // T x = a;
2169 if (DestType->isScalarType()) {
2170 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2171 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2172 return;
2173 }
2174
2175 // Assume scalar initialization from a single value works.
2176 } else if (DestType->isAggregateType()) {
2177 // Assume aggregate initialization works.
2178 } else if (DestType->isVectorType()) {
2179 // Assume vector initialization works.
2180 } else if (DestType->isReferenceType()) {
2181 // FIXME: C++0x defines behavior for this.
2182 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2183 return;
2184 } else if (DestType->isRecordType()) {
2185 // FIXME: C++0x defines behavior for this
2186 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2187 }
2188
2189 // Add a general "list initialization" step.
2190 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002191}
2192
2193/// \brief Try a reference initialization that involves calling a conversion
2194/// function.
2195///
2196/// FIXME: look intos DRs 656, 896
2197static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2198 const InitializedEntity &Entity,
2199 const InitializationKind &Kind,
2200 Expr *Initializer,
2201 bool AllowRValues,
2202 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002203 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002204 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2205 QualType T1 = cv1T1.getUnqualifiedType();
2206 QualType cv2T2 = Initializer->getType();
2207 QualType T2 = cv2T2.getUnqualifiedType();
2208
2209 bool DerivedToBase;
2210 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2211 T1, T2, DerivedToBase) &&
2212 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002213 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002214
2215 // Build the candidate set directly in the initialization sequence
2216 // structure, so that it will persist if we fail.
2217 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2218 CandidateSet.clear();
2219
2220 // Determine whether we are allowed to call explicit constructors or
2221 // explicit conversion operators.
2222 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2223
2224 const RecordType *T1RecordType = 0;
2225 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2226 // The type we're converting to is a class type. Enumerate its constructors
2227 // to see if there is a suitable conversion.
2228 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2229
2230 DeclarationName ConstructorName
2231 = S.Context.DeclarationNames.getCXXConstructorName(
2232 S.Context.getCanonicalType(T1).getUnqualifiedType());
2233 DeclContext::lookup_iterator Con, ConEnd;
2234 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2235 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002236 NamedDecl *D = *Con;
2237 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2238
Douglas Gregor20093b42009-12-09 23:02:17 +00002239 // Find the constructor (which may be a template).
2240 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002241 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002242 if (ConstructorTmpl)
2243 Constructor = cast<CXXConstructorDecl>(
2244 ConstructorTmpl->getTemplatedDecl());
2245 else
John McCall9aa472c2010-03-19 07:35:19 +00002246 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002247
2248 if (!Constructor->isInvalidDecl() &&
2249 Constructor->isConvertingConstructor(AllowExplicit)) {
2250 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002251 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002252 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002253 &Initializer, 1, CandidateSet);
2254 else
John McCall9aa472c2010-03-19 07:35:19 +00002255 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002256 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002257 }
2258 }
2259 }
2260
2261 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2262 // The type we're converting from is a class type, enumerate its conversion
2263 // functions.
2264 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2265
2266 // Determine the type we are converting to. If we are allowed to
2267 // convert to an rvalue, take the type that the destination type
2268 // refers to.
2269 QualType ToType = AllowRValues? cv1T1 : DestType;
2270
John McCalleec51cf2010-01-20 00:46:10 +00002271 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002272 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002273 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2274 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002275 NamedDecl *D = *I;
2276 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2277 if (isa<UsingShadowDecl>(D))
2278 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2279
2280 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2281 CXXConversionDecl *Conv;
2282 if (ConvTemplate)
2283 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2284 else
2285 Conv = cast<CXXConversionDecl>(*I);
2286
2287 // If the conversion function doesn't return a reference type,
2288 // it can't be considered for this conversion unless we're allowed to
2289 // consider rvalues.
2290 // FIXME: Do we need to make sure that we only consider conversion
2291 // candidates with reference-compatible results? That might be needed to
2292 // break recursion.
2293 if ((AllowExplicit || !Conv->isExplicit()) &&
2294 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2295 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002296 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002297 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002298 ToType, CandidateSet);
2299 else
John McCall9aa472c2010-03-19 07:35:19 +00002300 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002301 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002302 }
2303 }
2304 }
2305
2306 SourceLocation DeclLoc = Initializer->getLocStart();
2307
2308 // Perform overload resolution. If it fails, return the failed result.
2309 OverloadCandidateSet::iterator Best;
2310 if (OverloadingResult Result
2311 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2312 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002313
Douglas Gregor20093b42009-12-09 23:02:17 +00002314 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002315
2316 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002317 if (isa<CXXConversionDecl>(Function))
2318 T2 = Function->getResultType();
2319 else
2320 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002321
2322 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002323 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
John McCallb13b7372010-02-01 03:16:54 +00002324 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002325
2326 // Determine whether we need to perform derived-to-base or
2327 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002328 bool NewDerivedToBase = false;
2329 Sema::ReferenceCompareResult NewRefRelationship
2330 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2331 NewDerivedToBase);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002332 if (NewRefRelationship == Sema::Ref_Incompatible) {
2333 // If the type we've converted to is not reference-related to the
2334 // type we're looking for, then there is another conversion step
2335 // we need to perform to produce a temporary of the right type
2336 // that we'll be binding to.
2337 ImplicitConversionSequence ICS;
2338 ICS.setStandard();
2339 ICS.Standard = Best->FinalConversion;
2340 T2 = ICS.Standard.getToType(2);
2341 Sequence.AddConversionSequenceStep(ICS, T2);
2342 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002343 Sequence.AddDerivedToBaseCastStep(
2344 S.Context.getQualifiedType(T1,
2345 T2.getNonReferenceType().getQualifiers()),
2346 /*isLValue=*/true);
2347
2348 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2349 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2350
2351 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2352 return OR_Success;
2353}
2354
2355/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2356static void TryReferenceInitialization(Sema &S,
2357 const InitializedEntity &Entity,
2358 const InitializationKind &Kind,
2359 Expr *Initializer,
2360 InitializationSequence &Sequence) {
2361 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2362
Douglas Gregord6542d82009-12-22 15:35:07 +00002363 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002364 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002365 Qualifiers T1Quals;
2366 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002367 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002368 Qualifiers T2Quals;
2369 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002370 SourceLocation DeclLoc = Initializer->getLocStart();
2371
2372 // If the initializer is the address of an overloaded function, try
2373 // to resolve the overloaded function. If all goes well, T2 is the
2374 // type of the resulting function.
2375 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002376 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002377 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2378 T1,
John McCall6bb80172010-03-30 21:47:33 +00002379 false,
2380 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002381 if (!Fn) {
2382 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2383 return;
2384 }
2385
John McCall6bb80172010-03-30 21:47:33 +00002386 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002387 cv2T2 = Fn->getType();
2388 T2 = cv2T2.getUnqualifiedType();
2389 }
2390
2391 // FIXME: Rvalue references
2392 bool ForceRValue = false;
2393
2394 // Compute some basic properties of the types and the initializer.
2395 bool isLValueRef = DestType->isLValueReferenceType();
2396 bool isRValueRef = !isLValueRef;
2397 bool DerivedToBase = false;
2398 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2399 Initializer->isLvalue(S.Context);
2400 Sema::ReferenceCompareResult RefRelationship
2401 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2402
2403 // C++0x [dcl.init.ref]p5:
2404 // A reference to type "cv1 T1" is initialized by an expression of type
2405 // "cv2 T2" as follows:
2406 //
2407 // - If the reference is an lvalue reference and the initializer
2408 // expression
2409 OverloadingResult ConvOvlResult = OR_Success;
2410 if (isLValueRef) {
2411 if (InitLvalue == Expr::LV_Valid &&
2412 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2413 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2414 // reference-compatible with "cv2 T2," or
2415 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002416 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002417 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002418 // can occur. However, we do pay attention to whether it is a bit-field
2419 // to decide whether we're actually binding to a temporary created from
2420 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002421 if (DerivedToBase)
2422 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002423 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002424 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002425 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002426 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002427 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002428 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002429 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002430 return;
2431 }
2432
2433 // - has a class type (i.e., T2 is a class type), where T1 is not
2434 // reference-related to T2, and can be implicitly converted to an
2435 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2436 // with "cv3 T3" (this conversion is selected by enumerating the
2437 // applicable conversion functions (13.3.1.6) and choosing the best
2438 // one through overload resolution (13.3)),
2439 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2440 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2441 Initializer,
2442 /*AllowRValues=*/false,
2443 Sequence);
2444 if (ConvOvlResult == OR_Success)
2445 return;
John McCall1d318332010-01-12 00:44:57 +00002446 if (ConvOvlResult != OR_No_Viable_Function) {
2447 Sequence.SetOverloadFailure(
2448 InitializationSequence::FK_ReferenceInitOverloadFailed,
2449 ConvOvlResult);
2450 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002451 }
2452 }
2453
2454 // - Otherwise, the reference shall be an lvalue reference to a
2455 // non-volatile const type (i.e., cv1 shall be const), or the reference
2456 // shall be an rvalue reference and the initializer expression shall
2457 // be an rvalue.
Douglas Gregoref06e242010-01-29 19:39:15 +00002458 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002459 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2460 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2461 Sequence.SetOverloadFailure(
2462 InitializationSequence::FK_ReferenceInitOverloadFailed,
2463 ConvOvlResult);
2464 else if (isLValueRef)
2465 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2466 ? (RefRelationship == Sema::Ref_Related
2467 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2468 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2469 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2470 else
2471 Sequence.SetFailed(
2472 InitializationSequence::FK_RValueReferenceBindingToLValue);
2473
2474 return;
2475 }
2476
2477 // - If T1 and T2 are class types and
2478 if (T1->isRecordType() && T2->isRecordType()) {
2479 // - the initializer expression is an rvalue and "cv1 T1" is
2480 // reference-compatible with "cv2 T2", or
2481 if (InitLvalue != Expr::LV_Valid &&
2482 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2483 if (DerivedToBase)
2484 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002485 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002486 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002487 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002488 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2489 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2490 return;
2491 }
2492
2493 // - T1 is not reference-related to T2 and the initializer expression
2494 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2495 // conversion is selected by enumerating the applicable conversion
2496 // functions (13.3.1.6) and choosing the best one through overload
2497 // resolution (13.3)),
2498 if (RefRelationship == Sema::Ref_Incompatible) {
2499 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2500 Kind, Initializer,
2501 /*AllowRValues=*/true,
2502 Sequence);
2503 if (ConvOvlResult)
2504 Sequence.SetOverloadFailure(
2505 InitializationSequence::FK_ReferenceInitOverloadFailed,
2506 ConvOvlResult);
2507
2508 return;
2509 }
2510
2511 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2512 return;
2513 }
2514
2515 // - If the initializer expression is an rvalue, with T2 an array type,
2516 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2517 // is bound to the object represented by the rvalue (see 3.10).
2518 // FIXME: How can an array type be reference-compatible with anything?
2519 // Don't we mean the element types of T1 and T2?
2520
2521 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2522 // from the initializer expression using the rules for a non-reference
2523 // copy initialization (8.5). The reference is then bound to the
2524 // temporary. [...]
2525 // Determine whether we are allowed to call explicit constructors or
2526 // explicit conversion operators.
2527 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2528 ImplicitConversionSequence ICS
2529 = S.TryImplicitConversion(Initializer, cv1T1,
2530 /*SuppressUserConversions=*/false, AllowExplicit,
2531 /*ForceRValue=*/false,
2532 /*FIXME:InOverloadResolution=*/false,
2533 /*UserCast=*/Kind.isExplicitCast());
2534
John McCall1d318332010-01-12 00:44:57 +00002535 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 // FIXME: Use the conversion function set stored in ICS to turn
2537 // this into an overloading ambiguity diagnostic. However, we need
2538 // to keep that set as an OverloadCandidateSet rather than as some
2539 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002540 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2541 Sequence.SetOverloadFailure(
2542 InitializationSequence::FK_ReferenceInitOverloadFailed,
2543 ConvOvlResult);
2544 else
2545 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002546 return;
2547 }
2548
2549 // [...] If T1 is reference-related to T2, cv1 must be the
2550 // same cv-qualification as, or greater cv-qualification
2551 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002552 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2553 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002554 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002555 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002556 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2557 return;
2558 }
2559
2560 // Perform the actual conversion.
2561 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2562 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2563 return;
2564}
2565
2566/// \brief Attempt character array initialization from a string literal
2567/// (C++ [dcl.init.string], C99 6.7.8).
2568static void TryStringLiteralInitialization(Sema &S,
2569 const InitializedEntity &Entity,
2570 const InitializationKind &Kind,
2571 Expr *Initializer,
2572 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002573 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002574 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002575}
2576
Douglas Gregor20093b42009-12-09 23:02:17 +00002577/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2578/// enumerates the constructors of the initialized entity and performs overload
2579/// resolution to select the best.
2580static void TryConstructorInitialization(Sema &S,
2581 const InitializedEntity &Entity,
2582 const InitializationKind &Kind,
2583 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002584 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002585 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002586 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002587
2588 // Build the candidate set directly in the initialization sequence
2589 // structure, so that it will persist if we fail.
2590 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2591 CandidateSet.clear();
2592
2593 // Determine whether we are allowed to call explicit constructors or
2594 // explicit conversion operators.
2595 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2596 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002597 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002598
2599 // The type we're converting to is a class type. Enumerate its constructors
2600 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002601 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2602 assert(DestRecordType && "Constructor initialization requires record type");
2603 CXXRecordDecl *DestRecordDecl
2604 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2605
2606 DeclarationName ConstructorName
2607 = S.Context.DeclarationNames.getCXXConstructorName(
2608 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2609 DeclContext::lookup_iterator Con, ConEnd;
2610 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2611 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002612 NamedDecl *D = *Con;
2613 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2614
Douglas Gregor51c56d62009-12-14 20:49:26 +00002615 // Find the constructor (which may be a template).
2616 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002617 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002618 if (ConstructorTmpl)
2619 Constructor = cast<CXXConstructorDecl>(
2620 ConstructorTmpl->getTemplatedDecl());
2621 else
John McCall9aa472c2010-03-19 07:35:19 +00002622 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002623
2624 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002625 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002626 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002627 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002628 /*ExplicitArgs*/ 0,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002629 Args, NumArgs, CandidateSet);
2630 else
John McCall9aa472c2010-03-19 07:35:19 +00002631 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002632 Args, NumArgs, CandidateSet);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002633 }
2634 }
2635
2636 SourceLocation DeclLoc = Kind.getLocation();
2637
2638 // Perform overload resolution. If it fails, return the failed result.
2639 OverloadCandidateSet::iterator Best;
2640 if (OverloadingResult Result
2641 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2642 Sequence.SetOverloadFailure(
2643 InitializationSequence::FK_ConstructorOverloadFailed,
2644 Result);
2645 return;
2646 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002647
2648 // C++0x [dcl.init]p6:
2649 // If a program calls for the default initialization of an object
2650 // of a const-qualified type T, T shall be a class type with a
2651 // user-provided default constructor.
2652 if (Kind.getKind() == InitializationKind::IK_Default &&
2653 Entity.getType().isConstQualified() &&
2654 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2655 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2656 return;
2657 }
2658
Douglas Gregor51c56d62009-12-14 20:49:26 +00002659 // Add the constructor initialization step. Any cv-qualification conversion is
2660 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002661 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002662 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002663 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002664 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002665}
2666
Douglas Gregor71d17402009-12-15 00:01:57 +00002667/// \brief Attempt value initialization (C++ [dcl.init]p7).
2668static void TryValueInitialization(Sema &S,
2669 const InitializedEntity &Entity,
2670 const InitializationKind &Kind,
2671 InitializationSequence &Sequence) {
2672 // C++ [dcl.init]p5:
2673 //
2674 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002675 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002676
2677 // -- if T is an array type, then each element is value-initialized;
2678 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2679 T = AT->getElementType();
2680
2681 if (const RecordType *RT = T->getAs<RecordType>()) {
2682 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2683 // -- if T is a class type (clause 9) with a user-declared
2684 // constructor (12.1), then the default constructor for T is
2685 // called (and the initialization is ill-formed if T has no
2686 // accessible default constructor);
2687 //
2688 // FIXME: we really want to refer to a single subobject of the array,
2689 // but Entity doesn't have a way to capture that (yet).
2690 if (ClassDecl->hasUserDeclaredConstructor())
2691 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2692
Douglas Gregor16006c92009-12-16 18:50:27 +00002693 // -- if T is a (possibly cv-qualified) non-union class type
2694 // without a user-provided constructor, then the object is
2695 // zero-initialized and, if T’s implicitly-declared default
2696 // constructor is non-trivial, that constructor is called.
2697 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2698 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2699 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002700 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002701 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2702 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002703 }
2704 }
2705
Douglas Gregord6542d82009-12-22 15:35:07 +00002706 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002707 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2708}
2709
Douglas Gregor99a2e602009-12-16 01:38:02 +00002710/// \brief Attempt default initialization (C++ [dcl.init]p6).
2711static void TryDefaultInitialization(Sema &S,
2712 const InitializedEntity &Entity,
2713 const InitializationKind &Kind,
2714 InitializationSequence &Sequence) {
2715 assert(Kind.getKind() == InitializationKind::IK_Default);
2716
2717 // C++ [dcl.init]p6:
2718 // To default-initialize an object of type T means:
2719 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002720 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002721 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2722 DestType = Array->getElementType();
2723
2724 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2725 // constructor for T is called (and the initialization is ill-formed if
2726 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002727 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002728 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2729 Sequence);
2730 }
2731
2732 // - otherwise, no initialization is performed.
2733 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2734
2735 // If a program calls for the default initialization of an object of
2736 // a const-qualified type T, T shall be a class type with a user-provided
2737 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002738 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002739 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2740}
2741
Douglas Gregor20093b42009-12-09 23:02:17 +00002742/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2743/// which enumerates all conversion functions and performs overload resolution
2744/// to select the best.
2745static void TryUserDefinedConversion(Sema &S,
2746 const InitializedEntity &Entity,
2747 const InitializationKind &Kind,
2748 Expr *Initializer,
2749 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002750 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2751
Douglas Gregord6542d82009-12-22 15:35:07 +00002752 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002753 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2754 QualType SourceType = Initializer->getType();
2755 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2756 "Must have a class type to perform a user-defined conversion");
2757
2758 // Build the candidate set directly in the initialization sequence
2759 // structure, so that it will persist if we fail.
2760 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2761 CandidateSet.clear();
2762
2763 // Determine whether we are allowed to call explicit constructors or
2764 // explicit conversion operators.
2765 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2766
2767 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2768 // The type we're converting to is a class type. Enumerate its constructors
2769 // to see if there is a suitable conversion.
2770 CXXRecordDecl *DestRecordDecl
2771 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2772
2773 DeclarationName ConstructorName
2774 = S.Context.DeclarationNames.getCXXConstructorName(
2775 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2776 DeclContext::lookup_iterator Con, ConEnd;
2777 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2778 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002779 NamedDecl *D = *Con;
2780 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2781
Douglas Gregor4a520a22009-12-14 17:27:33 +00002782 // Find the constructor (which may be a template).
2783 CXXConstructorDecl *Constructor = 0;
2784 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002785 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002786 if (ConstructorTmpl)
2787 Constructor = cast<CXXConstructorDecl>(
2788 ConstructorTmpl->getTemplatedDecl());
2789 else
John McCall9aa472c2010-03-19 07:35:19 +00002790 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002791
2792 if (!Constructor->isInvalidDecl() &&
2793 Constructor->isConvertingConstructor(AllowExplicit)) {
2794 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002795 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002796 /*ExplicitArgs*/ 0,
Douglas Gregor4a520a22009-12-14 17:27:33 +00002797 &Initializer, 1, CandidateSet);
2798 else
John McCall9aa472c2010-03-19 07:35:19 +00002799 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002800 &Initializer, 1, CandidateSet);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002801 }
2802 }
2803 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002804
2805 SourceLocation DeclLoc = Initializer->getLocStart();
2806
Douglas Gregor4a520a22009-12-14 17:27:33 +00002807 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2808 // The type we're converting from is a class type, enumerate its conversion
2809 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002810
Eli Friedman33c2da92009-12-20 22:12:03 +00002811 // We can only enumerate the conversion functions for a complete type; if
2812 // the type isn't complete, simply skip this step.
2813 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2814 CXXRecordDecl *SourceRecordDecl
2815 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002816
John McCalleec51cf2010-01-20 00:46:10 +00002817 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002818 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002819 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002820 E = Conversions->end();
2821 I != E; ++I) {
2822 NamedDecl *D = *I;
2823 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2824 if (isa<UsingShadowDecl>(D))
2825 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2826
2827 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2828 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002829 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002830 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002831 else
John McCall32daa422010-03-31 01:36:47 +00002832 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002833
2834 if (AllowExplicit || !Conv->isExplicit()) {
2835 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002836 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002837 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002838 CandidateSet);
2839 else
John McCall9aa472c2010-03-19 07:35:19 +00002840 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002841 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002842 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002843 }
2844 }
2845 }
2846
Douglas Gregor4a520a22009-12-14 17:27:33 +00002847 // Perform overload resolution. If it fails, return the failed result.
2848 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002849 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002850 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2851 Sequence.SetOverloadFailure(
2852 InitializationSequence::FK_UserConversionOverloadFailed,
2853 Result);
2854 return;
2855 }
John McCall1d318332010-01-12 00:44:57 +00002856
Douglas Gregor4a520a22009-12-14 17:27:33 +00002857 FunctionDecl *Function = Best->Function;
2858
2859 if (isa<CXXConstructorDecl>(Function)) {
2860 // Add the user-defined conversion step. Any cv-qualification conversion is
2861 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002862 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002863 return;
2864 }
2865
2866 // Add the user-defined conversion step that calls the conversion function.
2867 QualType ConvType = Function->getResultType().getNonReferenceType();
John McCall9aa472c2010-03-19 07:35:19 +00002868 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002869
2870 // If the conversion following the call to the conversion function is
2871 // interesting, add it as a separate step.
2872 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2873 Best->FinalConversion.Third) {
2874 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002875 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002876 ICS.Standard = Best->FinalConversion;
2877 Sequence.AddConversionSequenceStep(ICS, DestType);
2878 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002879}
2880
2881/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2882/// non-class type to another.
2883static void TryImplicitConversion(Sema &S,
2884 const InitializedEntity &Entity,
2885 const InitializationKind &Kind,
2886 Expr *Initializer,
2887 InitializationSequence &Sequence) {
2888 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002889 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002890 /*SuppressUserConversions=*/true,
2891 /*AllowExplicit=*/false,
2892 /*ForceRValue=*/false,
2893 /*FIXME:InOverloadResolution=*/false,
2894 /*UserCast=*/Kind.isExplicitCast());
2895
John McCall1d318332010-01-12 00:44:57 +00002896 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2898 return;
2899 }
2900
Douglas Gregord6542d82009-12-22 15:35:07 +00002901 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002902}
2903
2904InitializationSequence::InitializationSequence(Sema &S,
2905 const InitializedEntity &Entity,
2906 const InitializationKind &Kind,
2907 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002908 unsigned NumArgs)
2909 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002910 ASTContext &Context = S.Context;
2911
2912 // C++0x [dcl.init]p16:
2913 // The semantics of initializers are as follows. The destination type is
2914 // the type of the object or reference being initialized and the source
2915 // type is the type of the initializer expression. The source type is not
2916 // defined when the initializer is a braced-init-list or when it is a
2917 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002918 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002919
2920 if (DestType->isDependentType() ||
2921 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2922 SequenceKind = DependentSequence;
2923 return;
2924 }
2925
2926 QualType SourceType;
2927 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002928 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002929 Initializer = Args[0];
2930 if (!isa<InitListExpr>(Initializer))
2931 SourceType = Initializer->getType();
2932 }
2933
2934 // - If the initializer is a braced-init-list, the object is
2935 // list-initialized (8.5.4).
2936 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2937 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002938 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002939 }
2940
2941 // - If the destination type is a reference type, see 8.5.3.
2942 if (DestType->isReferenceType()) {
2943 // C++0x [dcl.init.ref]p1:
2944 // A variable declared to be a T& or T&&, that is, "reference to type T"
2945 // (8.3.2), shall be initialized by an object, or function, of type T or
2946 // by an object that can be converted into a T.
2947 // (Therefore, multiple arguments are not permitted.)
2948 if (NumArgs != 1)
2949 SetFailed(FK_TooManyInitsForReference);
2950 else
2951 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2952 return;
2953 }
2954
2955 // - If the destination type is an array of characters, an array of
2956 // char16_t, an array of char32_t, or an array of wchar_t, and the
2957 // initializer is a string literal, see 8.5.2.
2958 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2959 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2960 return;
2961 }
2962
2963 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002964 if (Kind.getKind() == InitializationKind::IK_Value ||
2965 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002966 TryValueInitialization(S, Entity, Kind, *this);
2967 return;
2968 }
2969
Douglas Gregor99a2e602009-12-16 01:38:02 +00002970 // Handle default initialization.
2971 if (Kind.getKind() == InitializationKind::IK_Default){
2972 TryDefaultInitialization(S, Entity, Kind, *this);
2973 return;
2974 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002975
Douglas Gregor20093b42009-12-09 23:02:17 +00002976 // - Otherwise, if the destination type is an array, the program is
2977 // ill-formed.
2978 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2979 if (AT->getElementType()->isAnyCharacterType())
2980 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2981 else
2982 SetFailed(FK_ArrayNeedsInitList);
2983
2984 return;
2985 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002986
2987 // Handle initialization in C
2988 if (!S.getLangOptions().CPlusPlus) {
2989 setSequenceKind(CAssignment);
2990 AddCAssignmentStep(DestType);
2991 return;
2992 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002993
2994 // - If the destination type is a (possibly cv-qualified) class type:
2995 if (DestType->isRecordType()) {
2996 // - If the initialization is direct-initialization, or if it is
2997 // copy-initialization where the cv-unqualified version of the
2998 // source type is the same class as, or a derived class of, the
2999 // class of the destination, constructors are considered. [...]
3000 if (Kind.getKind() == InitializationKind::IK_Direct ||
3001 (Kind.getKind() == InitializationKind::IK_Copy &&
3002 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3003 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003004 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003005 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003006 // - Otherwise (i.e., for the remaining copy-initialization cases),
3007 // user-defined conversion sequences that can convert from the source
3008 // type to the destination type or (when a conversion function is
3009 // used) to a derived class thereof are enumerated as described in
3010 // 13.3.1.4, and the best one is chosen through overload resolution
3011 // (13.3).
3012 else
3013 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3014 return;
3015 }
3016
Douglas Gregor99a2e602009-12-16 01:38:02 +00003017 if (NumArgs > 1) {
3018 SetFailed(FK_TooManyInitsForScalar);
3019 return;
3020 }
3021 assert(NumArgs == 1 && "Zero-argument case handled above");
3022
Douglas Gregor20093b42009-12-09 23:02:17 +00003023 // - Otherwise, if the source type is a (possibly cv-qualified) class
3024 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003025 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003026 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3027 return;
3028 }
3029
3030 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003031 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003032 // conversions (Clause 4) will be used, if necessary, to convert the
3033 // initializer expression to the cv-unqualified version of the
3034 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003035 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003036 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
3037}
3038
3039InitializationSequence::~InitializationSequence() {
3040 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3041 StepEnd = Steps.end();
3042 Step != StepEnd; ++Step)
3043 Step->Destroy();
3044}
3045
3046//===----------------------------------------------------------------------===//
3047// Perform initialization
3048//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003049static Sema::AssignmentAction
3050getAssignmentAction(const InitializedEntity &Entity) {
3051 switch(Entity.getKind()) {
3052 case InitializedEntity::EK_Variable:
3053 case InitializedEntity::EK_New:
3054 return Sema::AA_Initializing;
3055
3056 case InitializedEntity::EK_Parameter:
3057 // FIXME: Can we tell when we're sending vs. passing?
3058 return Sema::AA_Passing;
3059
3060 case InitializedEntity::EK_Result:
3061 return Sema::AA_Returning;
3062
3063 case InitializedEntity::EK_Exception:
3064 case InitializedEntity::EK_Base:
3065 llvm_unreachable("No assignment action for C++-specific initialization");
3066 break;
3067
3068 case InitializedEntity::EK_Temporary:
3069 // FIXME: Can we tell apart casting vs. converting?
3070 return Sema::AA_Casting;
3071
3072 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003073 case InitializedEntity::EK_ArrayElement:
3074 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003075 return Sema::AA_Initializing;
3076 }
3077
3078 return Sema::AA_Converting;
3079}
3080
Douglas Gregor2f599792010-04-02 18:24:57 +00003081static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003082 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003083 case InitializedEntity::EK_ArrayElement:
3084 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003085 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003086 case InitializedEntity::EK_New:
3087 case InitializedEntity::EK_Variable:
3088 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003089 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003090 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003091 return false;
3092
3093 case InitializedEntity::EK_Parameter:
3094 case InitializedEntity::EK_Temporary:
3095 return true;
3096 }
3097
3098 llvm_unreachable("missed an InitializedEntity kind?");
3099}
3100
Douglas Gregor2f599792010-04-02 18:24:57 +00003101static Sema::OwningExprResult CopyObject(Sema &S,
3102 const InitializedEntity &Entity,
3103 const InitializationKind &Kind,
3104 Sema::OwningExprResult CurInit) {
3105 // Determine which class type we're copying.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003106 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003107 CXXRecordDecl *Class = 0;
3108 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3109 Class = cast<CXXRecordDecl>(Record->getDecl());
3110 if (!Class)
3111 return move(CurInit);
3112
3113 // C++0x [class.copy]p34:
3114 // When certain criteria are met, an implementation is allowed to
3115 // omit the copy/move construction of a class object, even if the
3116 // copy/move constructor and/or destructor for the object have
3117 // side effects. [...]
3118 // - when a temporary class object that has not been bound to a
3119 // reference (12.2) would be copied/moved to a class object
3120 // with the same cv-unqualified type, the copy/move operation
3121 // can be omitted by constructing the temporary object
3122 // directly into the target of the omitted copy/move
3123 //
3124 // Note that the other three bullets are handled elsewhere. Copy
3125 // elision for return statements and throw expressions are (FIXME:
3126 // not yet) handled as part of constructor initialization, while
3127 // copy elision for exception handlers is handled by the run-time.
3128 bool Elidable = CurInitExpr->isTemporaryObject() &&
3129 S.Context.hasSameUnqualifiedType(Entity.getType(), CurInitExpr->getType());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003130 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003131 switch (Entity.getKind()) {
3132 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003133 Loc = Entity.getReturnLoc();
3134 break;
3135
3136 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003137 Loc = Entity.getThrowLoc();
3138 break;
3139
3140 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003141 Loc = Entity.getDecl()->getLocation();
3142 break;
3143
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003144 case InitializedEntity::EK_ArrayElement:
3145 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003146 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003147 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003148 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003149 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003150 case InitializedEntity::EK_VectorElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003151 Loc = CurInitExpr->getLocStart();
3152 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003153 }
Douglas Gregor2f599792010-04-02 18:24:57 +00003154
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003155 // Perform overload resolution using the class's copy constructors.
3156 DeclarationName ConstructorName
3157 = S.Context.DeclarationNames.getCXXConstructorName(
3158 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3159 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003160 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003161 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3162 Con != ConEnd; ++Con) {
Douglas Gregor2f599792010-04-02 18:24:57 +00003163 // Only consider copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003164 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3165 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003166 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003167 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003168
3169 DeclAccessPair FoundDecl
3170 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3171 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003172 &CurInitExpr, 1, CandidateSet);
Douglas Gregor2f599792010-04-02 18:24:57 +00003173 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003174
3175 OverloadCandidateSet::iterator Best;
3176 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3177 case OR_Success:
3178 break;
3179
3180 case OR_No_Viable_Function:
3181 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003182 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003183 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003184 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3185 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003186 return S.ExprError();
3187
3188 case OR_Ambiguous:
3189 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003190 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003191 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003192 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3193 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003194 return S.ExprError();
3195
3196 case OR_Deleted:
3197 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003198 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003199 << CurInitExpr->getSourceRange();
3200 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3201 << Best->Function->isDeleted();
3202 return S.ExprError();
3203 }
3204
John McCall9aa472c2010-03-19 07:35:19 +00003205 S.CheckConstructorAccess(Loc,
3206 cast<CXXConstructorDecl>(Best->Function),
3207 Best->FoundDecl.getAccess());
3208
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003209 CurInit.release();
Douglas Gregor2f599792010-04-02 18:24:57 +00003210 return S.BuildCXXConstructExpr(Loc, Entity.getType().getNonReferenceType(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003211 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor2f599792010-04-02 18:24:57 +00003212 Elidable,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003213 Sema::MultiExprArg(S,
3214 (void**)&CurInitExpr, 1));
3215}
Douglas Gregor20093b42009-12-09 23:02:17 +00003216
3217Action::OwningExprResult
3218InitializationSequence::Perform(Sema &S,
3219 const InitializedEntity &Entity,
3220 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003221 Action::MultiExprArg Args,
3222 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003223 if (SequenceKind == FailedSequence) {
3224 unsigned NumArgs = Args.size();
3225 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3226 return S.ExprError();
3227 }
3228
3229 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003230 // If the declaration is a non-dependent, incomplete array type
3231 // that has an initializer, then its type will be completed once
3232 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003233 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003234 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003235 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003236 if (const IncompleteArrayType *ArrayT
3237 = S.Context.getAsIncompleteArrayType(DeclType)) {
3238 // FIXME: We don't currently have the ability to accurately
3239 // compute the length of an initializer list without
3240 // performing full type-checking of the initializer list
3241 // (since we have to determine where braces are implicitly
3242 // introduced and such). So, we fall back to making the array
3243 // type a dependently-sized array type with no specified
3244 // bound.
3245 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3246 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003247
Douglas Gregord87b61f2009-12-10 17:56:55 +00003248 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003249 if (DeclaratorDecl *DD = Entity.getDecl()) {
3250 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3251 TypeLoc TL = TInfo->getTypeLoc();
3252 if (IncompleteArrayTypeLoc *ArrayLoc
3253 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3254 Brackets = ArrayLoc->getBracketsRange();
3255 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003256 }
3257
3258 *ResultType
3259 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3260 /*NumElts=*/0,
3261 ArrayT->getSizeModifier(),
3262 ArrayT->getIndexTypeCVRQualifiers(),
3263 Brackets);
3264 }
3265
3266 }
3267 }
3268
Eli Friedman08544622009-12-22 02:35:53 +00003269 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003270 return Sema::OwningExprResult(S, Args.release()[0]);
3271
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003272 if (Args.size() == 0)
3273 return S.Owned((Expr *)0);
3274
Douglas Gregor20093b42009-12-09 23:02:17 +00003275 unsigned NumArgs = Args.size();
3276 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3277 SourceLocation(),
3278 (Expr **)Args.release(),
3279 NumArgs,
3280 SourceLocation()));
3281 }
3282
Douglas Gregor99a2e602009-12-16 01:38:02 +00003283 if (SequenceKind == NoInitialization)
3284 return S.Owned((Expr *)0);
3285
Douglas Gregord6542d82009-12-22 15:35:07 +00003286 QualType DestType = Entity.getType().getNonReferenceType();
3287 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003288 // the same as Entity.getDecl()->getType() in cases involving type merging,
3289 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003290 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003291 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003292 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003293
Douglas Gregor99a2e602009-12-16 01:38:02 +00003294 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3295
3296 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3297
3298 // For initialization steps that start with a single initializer,
3299 // grab the only argument out the Args and place it into the "current"
3300 // initializer.
3301 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003302 case SK_ResolveAddressOfOverloadedFunction:
3303 case SK_CastDerivedToBaseRValue:
3304 case SK_CastDerivedToBaseLValue:
3305 case SK_BindReference:
3306 case SK_BindReferenceToTemporary:
3307 case SK_UserConversion:
3308 case SK_QualificationConversionLValue:
3309 case SK_QualificationConversionRValue:
3310 case SK_ConversionSequence:
3311 case SK_ListInitialization:
3312 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003313 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003314 assert(Args.size() == 1);
3315 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3316 if (CurInit.isInvalid())
3317 return S.ExprError();
3318 break;
3319
3320 case SK_ConstructorInitialization:
3321 case SK_ZeroInitialization:
3322 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003323 }
3324
3325 // Walk through the computed steps for the initialization sequence,
3326 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003327 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003328 for (step_iterator Step = step_begin(), StepEnd = step_end();
3329 Step != StepEnd; ++Step) {
3330 if (CurInit.isInvalid())
3331 return S.ExprError();
3332
3333 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003334 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003335
3336 switch (Step->Kind) {
3337 case SK_ResolveAddressOfOverloadedFunction:
3338 // Overload resolution determined which function invoke; update the
3339 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003340 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb13b7372010-02-01 03:16:54 +00003341 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003342 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003343 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003344 break;
3345
3346 case SK_CastDerivedToBaseRValue:
3347 case SK_CastDerivedToBaseLValue: {
3348 // We have a derived-to-base cast that produces either an rvalue or an
3349 // lvalue. Perform that cast.
3350
3351 // Casts to inaccessible base classes are allowed with C-style casts.
3352 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3353 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3354 CurInitExpr->getLocStart(),
3355 CurInitExpr->getSourceRange(),
3356 IgnoreBaseAccess))
3357 return S.ExprError();
3358
3359 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3360 CastExpr::CK_DerivedToBase,
3361 (Expr*)CurInit.release(),
3362 Step->Kind == SK_CastDerivedToBaseLValue));
3363 break;
3364 }
3365
3366 case SK_BindReference:
3367 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3368 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3369 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003370 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003371 << BitField->getDeclName()
3372 << CurInitExpr->getSourceRange();
3373 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3374 return S.ExprError();
3375 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003376
Anders Carlsson09380262010-01-31 17:18:49 +00003377 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003378 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003379 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3380 << Entity.getType().isVolatileQualified()
3381 << CurInitExpr->getSourceRange();
3382 return S.ExprError();
3383 }
3384
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 // Reference binding does not have any corresponding ASTs.
3386
3387 // Check exception specifications
3388 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3389 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003390
Douglas Gregor20093b42009-12-09 23:02:17 +00003391 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003392
Douglas Gregor20093b42009-12-09 23:02:17 +00003393 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003394 // Reference binding does not have any corresponding ASTs.
3395
Douglas Gregor20093b42009-12-09 23:02:17 +00003396 // Check exception specifications
3397 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3398 return S.ExprError();
3399
Douglas Gregor20093b42009-12-09 23:02:17 +00003400 break;
3401
3402 case SK_UserConversion: {
3403 // We have a user-defined conversion that invokes either a constructor
3404 // or a conversion function.
3405 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003406 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003407 FunctionDecl *Fn = Step->Function.Function;
3408 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003409 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003410 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003411 // Build a call to the selected constructor.
3412 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3413 SourceLocation Loc = CurInitExpr->getLocStart();
3414 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003415
Douglas Gregor20093b42009-12-09 23:02:17 +00003416 // Determine the arguments required to actually perform the constructor
3417 // call.
3418 if (S.CompleteConstructorCall(Constructor,
3419 Sema::MultiExprArg(S,
3420 (void **)&CurInitExpr,
3421 1),
3422 Loc, ConstructorArgs))
3423 return S.ExprError();
3424
3425 // Build the an expression that constructs a temporary.
3426 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3427 move_arg(ConstructorArgs));
3428 if (CurInit.isInvalid())
3429 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003430
John McCall9aa472c2010-03-19 07:35:19 +00003431 S.CheckConstructorAccess(Kind.getLocation(), Constructor,
3432 FoundFn.getAccess());
Douglas Gregor20093b42009-12-09 23:02:17 +00003433
3434 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003435 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3436 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3437 S.IsDerivedFrom(SourceType, Class))
3438 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003439 } else {
3440 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003441 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003442 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003443 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003444 FoundFn);
John McCallb13b7372010-02-01 03:16:54 +00003445
Douglas Gregor20093b42009-12-09 23:02:17 +00003446 // FIXME: Should we move this initialization into a separate
3447 // derived-to-base conversion? I believe the answer is "no", because
3448 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003449 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003450 FoundFn, Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003451 return S.ExprError();
3452
3453 // Do a little dance to make sure that CurInit has the proper
3454 // pointer.
3455 CurInit.release();
3456
3457 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003458 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3459 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003460 if (CurInit.isInvalid() || !CurInit.get())
3461 return S.ExprError();
3462
3463 CastKind = CastExpr::CK_UserDefinedConversion;
3464 }
3465
Douglas Gregor2f599792010-04-02 18:24:57 +00003466 bool RequiresCopy = !IsCopy &&
3467 getKind() != InitializationSequence::ReferenceBinding;
3468 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003469 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3470
Douglas Gregor20093b42009-12-09 23:02:17 +00003471 CurInitExpr = CurInit.takeAs<Expr>();
3472 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3473 CastKind,
3474 CurInitExpr,
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003475 IsLvalue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003476
Douglas Gregor2f599792010-04-02 18:24:57 +00003477 if (RequiresCopy)
3478 CurInit = CopyObject(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 break;
3480 }
3481
3482 case SK_QualificationConversionLValue:
3483 case SK_QualificationConversionRValue:
3484 // Perform a qualification conversion; these can never go wrong.
3485 S.ImpCastExprToType(CurInitExpr, Step->Type,
3486 CastExpr::CK_NoOp,
3487 Step->Kind == SK_QualificationConversionLValue);
3488 CurInit.release();
3489 CurInit = S.Owned(CurInitExpr);
3490 break;
3491
3492 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003493 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003494 false, false, *Step->ICS))
3495 return S.ExprError();
3496
3497 CurInit.release();
3498 CurInit = S.Owned(CurInitExpr);
3499 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003500
3501 case SK_ListInitialization: {
3502 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3503 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003504 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003505 return S.ExprError();
3506
3507 CurInit.release();
3508 CurInit = S.Owned(InitList);
3509 break;
3510 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003511
3512 case SK_ConstructorInitialization: {
3513 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003514 = cast<CXXConstructorDecl>(Step->Function.Function);
John McCallb13b7372010-02-01 03:16:54 +00003515
Douglas Gregor51c56d62009-12-14 20:49:26 +00003516 // Build a call to the selected constructor.
3517 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3518 SourceLocation Loc = Kind.getLocation();
3519
3520 // Determine the arguments required to actually perform the constructor
3521 // call.
3522 if (S.CompleteConstructorCall(Constructor, move(Args),
3523 Loc, ConstructorArgs))
3524 return S.ExprError();
3525
3526 // Build the an expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003527 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
3528 (Kind.getKind() == InitializationKind::IK_Direct ||
3529 Kind.getKind() == InitializationKind::IK_Value)) {
3530 // An explicitly-constructed temporary, e.g., X(1, 2).
3531 unsigned NumExprs = ConstructorArgs.size();
3532 Expr **Exprs = (Expr **)ConstructorArgs.take();
3533 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3534 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3535 Constructor,
3536 Entity.getType(),
3537 Kind.getLocation(),
3538 Exprs,
3539 NumExprs,
3540 Kind.getParenRange().getEnd()));
3541 } else
3542 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3543 Constructor,
3544 move_arg(ConstructorArgs),
3545 ConstructorInitRequiresZeroInit,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003546 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003547 if (CurInit.isInvalid())
3548 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003549
3550 // Only check access if all of that succeeded.
John McCall9aa472c2010-03-19 07:35:19 +00003551 S.CheckConstructorAccess(Loc, Constructor,
3552 Step->Function.FoundDecl.getAccess());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003553
Douglas Gregor2f599792010-04-02 18:24:57 +00003554 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003555 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00003556
Douglas Gregor51c56d62009-12-14 20:49:26 +00003557 break;
3558 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003559
3560 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003561 step_iterator NextStep = Step;
3562 ++NextStep;
3563 if (NextStep != StepEnd &&
3564 NextStep->Kind == SK_ConstructorInitialization) {
3565 // The need for zero-initialization is recorded directly into
3566 // the call to the object's constructor within the next step.
3567 ConstructorInitRequiresZeroInit = true;
3568 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3569 S.getLangOptions().CPlusPlus &&
3570 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003571 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3572 Kind.getRange().getBegin(),
3573 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003574 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003575 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003576 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003577 break;
3578 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003579
3580 case SK_CAssignment: {
3581 QualType SourceType = CurInitExpr->getType();
3582 Sema::AssignConvertType ConvTy =
3583 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003584
3585 // If this is a call, allow conversion to a transparent union.
3586 if (ConvTy != Sema::Compatible &&
3587 Entity.getKind() == InitializedEntity::EK_Parameter &&
3588 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3589 == Sema::Compatible)
3590 ConvTy = Sema::Compatible;
3591
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003592 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3593 Step->Type, SourceType,
3594 CurInitExpr, getAssignmentAction(Entity)))
3595 return S.ExprError();
3596
3597 CurInit.release();
3598 CurInit = S.Owned(CurInitExpr);
3599 break;
3600 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003601
3602 case SK_StringInit: {
3603 QualType Ty = Step->Type;
3604 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3605 break;
3606 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003607 }
3608 }
3609
3610 return move(CurInit);
3611}
3612
3613//===----------------------------------------------------------------------===//
3614// Diagnose initialization failures
3615//===----------------------------------------------------------------------===//
3616bool InitializationSequence::Diagnose(Sema &S,
3617 const InitializedEntity &Entity,
3618 const InitializationKind &Kind,
3619 Expr **Args, unsigned NumArgs) {
3620 if (SequenceKind != FailedSequence)
3621 return false;
3622
Douglas Gregord6542d82009-12-22 15:35:07 +00003623 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 switch (Failure) {
3625 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003626 // FIXME: Customize for the initialized entity?
3627 if (NumArgs == 0)
3628 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3629 << DestType.getNonReferenceType();
3630 else // FIXME: diagnostic below could be better!
3631 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3632 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003633 break;
3634
3635 case FK_ArrayNeedsInitList:
3636 case FK_ArrayNeedsInitListOrStringLiteral:
3637 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3638 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3639 break;
3640
John McCall6bb80172010-03-30 21:47:33 +00003641 case FK_AddressOfOverloadFailed: {
3642 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003643 S.ResolveAddressOfOverloadedFunction(Args[0],
3644 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003645 true,
3646 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003647 break;
John McCall6bb80172010-03-30 21:47:33 +00003648 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003649
3650 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003651 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003652 switch (FailedOverloadResult) {
3653 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003654 if (Failure == FK_UserConversionOverloadFailed)
3655 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3656 << Args[0]->getType() << DestType
3657 << Args[0]->getSourceRange();
3658 else
3659 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3660 << DestType << Args[0]->getType()
3661 << Args[0]->getSourceRange();
3662
John McCallcbce6062010-01-12 07:18:19 +00003663 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3664 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003665 break;
3666
3667 case OR_No_Viable_Function:
3668 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3669 << Args[0]->getType() << DestType.getNonReferenceType()
3670 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003671 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3672 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003673 break;
3674
3675 case OR_Deleted: {
3676 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3677 << Args[0]->getType() << DestType.getNonReferenceType()
3678 << Args[0]->getSourceRange();
3679 OverloadCandidateSet::iterator Best;
3680 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3681 Kind.getLocation(),
3682 Best);
3683 if (Ovl == OR_Deleted) {
3684 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3685 << Best->Function->isDeleted();
3686 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003687 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 }
3689 break;
3690 }
3691
3692 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003693 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003694 break;
3695 }
3696 break;
3697
3698 case FK_NonConstLValueReferenceBindingToTemporary:
3699 case FK_NonConstLValueReferenceBindingToUnrelated:
3700 S.Diag(Kind.getLocation(),
3701 Failure == FK_NonConstLValueReferenceBindingToTemporary
3702 ? diag::err_lvalue_reference_bind_to_temporary
3703 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003704 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003705 << DestType.getNonReferenceType()
3706 << Args[0]->getType()
3707 << Args[0]->getSourceRange();
3708 break;
3709
3710 case FK_RValueReferenceBindingToLValue:
3711 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3712 << Args[0]->getSourceRange();
3713 break;
3714
3715 case FK_ReferenceInitDropsQualifiers:
3716 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3717 << DestType.getNonReferenceType()
3718 << Args[0]->getType()
3719 << Args[0]->getSourceRange();
3720 break;
3721
3722 case FK_ReferenceInitFailed:
3723 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3724 << DestType.getNonReferenceType()
3725 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3726 << Args[0]->getType()
3727 << Args[0]->getSourceRange();
3728 break;
3729
3730 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003731 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3732 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003733 << DestType
3734 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3735 << Args[0]->getType()
3736 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003737 break;
3738
3739 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003740 SourceRange R;
3741
3742 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3743 R = SourceRange(InitList->getInit(1)->getLocStart(),
3744 InitList->getLocEnd());
3745 else
3746 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003747
3748 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003749 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003750 break;
3751 }
3752
3753 case FK_ReferenceBindingToInitList:
3754 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3755 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3756 break;
3757
3758 case FK_InitListBadDestinationType:
3759 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3760 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3761 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003762
3763 case FK_ConstructorOverloadFailed: {
3764 SourceRange ArgsRange;
3765 if (NumArgs)
3766 ArgsRange = SourceRange(Args[0]->getLocStart(),
3767 Args[NumArgs - 1]->getLocEnd());
3768
3769 // FIXME: Using "DestType" for the entity we're printing is probably
3770 // bad.
3771 switch (FailedOverloadResult) {
3772 case OR_Ambiguous:
3773 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3774 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003775 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003776 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003777 break;
3778
3779 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003780 if (Kind.getKind() == InitializationKind::IK_Default &&
3781 (Entity.getKind() == InitializedEntity::EK_Base ||
3782 Entity.getKind() == InitializedEntity::EK_Member) &&
3783 isa<CXXConstructorDecl>(S.CurContext)) {
3784 // This is implicit default initialization of a member or
3785 // base within a constructor. If no viable function was
3786 // found, notify the user that she needs to explicitly
3787 // initialize this base/member.
3788 CXXConstructorDecl *Constructor
3789 = cast<CXXConstructorDecl>(S.CurContext);
3790 if (Entity.getKind() == InitializedEntity::EK_Base) {
3791 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3792 << Constructor->isImplicit()
3793 << S.Context.getTypeDeclType(Constructor->getParent())
3794 << /*base=*/0
3795 << Entity.getType();
3796
3797 RecordDecl *BaseDecl
3798 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3799 ->getDecl();
3800 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
3801 << S.Context.getTagDeclType(BaseDecl);
3802 } else {
3803 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3804 << Constructor->isImplicit()
3805 << S.Context.getTypeDeclType(Constructor->getParent())
3806 << /*member=*/1
3807 << Entity.getName();
3808 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
3809
3810 if (const RecordType *Record
3811 = Entity.getType()->getAs<RecordType>())
3812 S.Diag(Record->getDecl()->getLocation(),
3813 diag::note_previous_decl)
3814 << S.Context.getTagDeclType(Record->getDecl());
3815 }
3816 break;
3817 }
3818
Douglas Gregor51c56d62009-12-14 20:49:26 +00003819 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3820 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003821 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3822 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003823 break;
3824
3825 case OR_Deleted: {
3826 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3827 << true << DestType << ArgsRange;
3828 OverloadCandidateSet::iterator Best;
3829 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3830 Kind.getLocation(),
3831 Best);
3832 if (Ovl == OR_Deleted) {
3833 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3834 << Best->Function->isDeleted();
3835 } else {
3836 llvm_unreachable("Inconsistent overload resolution?");
3837 }
3838 break;
3839 }
3840
3841 case OR_Success:
3842 llvm_unreachable("Conversion did not fail!");
3843 break;
3844 }
3845 break;
3846 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003847
3848 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003849 if (Entity.getKind() == InitializedEntity::EK_Member &&
3850 isa<CXXConstructorDecl>(S.CurContext)) {
3851 // This is implicit default-initialization of a const member in
3852 // a constructor. Complain that it needs to be explicitly
3853 // initialized.
3854 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
3855 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
3856 << Constructor->isImplicit()
3857 << S.Context.getTypeDeclType(Constructor->getParent())
3858 << /*const=*/1
3859 << Entity.getName();
3860 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
3861 << Entity.getName();
3862 } else {
3863 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3864 << DestType << (bool)DestType->getAs<RecordType>();
3865 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003866 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003867 }
3868
3869 return true;
3870}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003871
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003872void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3873 switch (SequenceKind) {
3874 case FailedSequence: {
3875 OS << "Failed sequence: ";
3876 switch (Failure) {
3877 case FK_TooManyInitsForReference:
3878 OS << "too many initializers for reference";
3879 break;
3880
3881 case FK_ArrayNeedsInitList:
3882 OS << "array requires initializer list";
3883 break;
3884
3885 case FK_ArrayNeedsInitListOrStringLiteral:
3886 OS << "array requires initializer list or string literal";
3887 break;
3888
3889 case FK_AddressOfOverloadFailed:
3890 OS << "address of overloaded function failed";
3891 break;
3892
3893 case FK_ReferenceInitOverloadFailed:
3894 OS << "overload resolution for reference initialization failed";
3895 break;
3896
3897 case FK_NonConstLValueReferenceBindingToTemporary:
3898 OS << "non-const lvalue reference bound to temporary";
3899 break;
3900
3901 case FK_NonConstLValueReferenceBindingToUnrelated:
3902 OS << "non-const lvalue reference bound to unrelated type";
3903 break;
3904
3905 case FK_RValueReferenceBindingToLValue:
3906 OS << "rvalue reference bound to an lvalue";
3907 break;
3908
3909 case FK_ReferenceInitDropsQualifiers:
3910 OS << "reference initialization drops qualifiers";
3911 break;
3912
3913 case FK_ReferenceInitFailed:
3914 OS << "reference initialization failed";
3915 break;
3916
3917 case FK_ConversionFailed:
3918 OS << "conversion failed";
3919 break;
3920
3921 case FK_TooManyInitsForScalar:
3922 OS << "too many initializers for scalar";
3923 break;
3924
3925 case FK_ReferenceBindingToInitList:
3926 OS << "referencing binding to initializer list";
3927 break;
3928
3929 case FK_InitListBadDestinationType:
3930 OS << "initializer list for non-aggregate, non-scalar type";
3931 break;
3932
3933 case FK_UserConversionOverloadFailed:
3934 OS << "overloading failed for user-defined conversion";
3935 break;
3936
3937 case FK_ConstructorOverloadFailed:
3938 OS << "constructor overloading failed";
3939 break;
3940
3941 case FK_DefaultInitOfConst:
3942 OS << "default initialization of a const variable";
3943 break;
3944 }
3945 OS << '\n';
3946 return;
3947 }
3948
3949 case DependentSequence:
3950 OS << "Dependent sequence: ";
3951 return;
3952
3953 case UserDefinedConversion:
3954 OS << "User-defined conversion sequence: ";
3955 break;
3956
3957 case ConstructorInitialization:
3958 OS << "Constructor initialization sequence: ";
3959 break;
3960
3961 case ReferenceBinding:
3962 OS << "Reference binding: ";
3963 break;
3964
3965 case ListInitialization:
3966 OS << "List initialization: ";
3967 break;
3968
3969 case ZeroInitialization:
3970 OS << "Zero initialization\n";
3971 return;
3972
3973 case NoInitialization:
3974 OS << "No initialization\n";
3975 return;
3976
3977 case StandardConversion:
3978 OS << "Standard conversion: ";
3979 break;
3980
3981 case CAssignment:
3982 OS << "C assignment: ";
3983 break;
3984
3985 case StringInit:
3986 OS << "String initialization: ";
3987 break;
3988 }
3989
3990 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
3991 if (S != step_begin()) {
3992 OS << " -> ";
3993 }
3994
3995 switch (S->Kind) {
3996 case SK_ResolveAddressOfOverloadedFunction:
3997 OS << "resolve address of overloaded function";
3998 break;
3999
4000 case SK_CastDerivedToBaseRValue:
4001 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4002 break;
4003
4004 case SK_CastDerivedToBaseLValue:
4005 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4006 break;
4007
4008 case SK_BindReference:
4009 OS << "bind reference to lvalue";
4010 break;
4011
4012 case SK_BindReferenceToTemporary:
4013 OS << "bind reference to a temporary";
4014 break;
4015
4016 case SK_UserConversion:
John McCall9aa472c2010-03-19 07:35:19 +00004017 OS << "user-defined conversion via "
4018 << S->Function.Function->getNameAsString();
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004019 break;
4020
4021 case SK_QualificationConversionRValue:
4022 OS << "qualification conversion (rvalue)";
4023
4024 case SK_QualificationConversionLValue:
4025 OS << "qualification conversion (lvalue)";
4026 break;
4027
4028 case SK_ConversionSequence:
4029 OS << "implicit conversion sequence (";
4030 S->ICS->DebugPrint(); // FIXME: use OS
4031 OS << ")";
4032 break;
4033
4034 case SK_ListInitialization:
4035 OS << "list initialization";
4036 break;
4037
4038 case SK_ConstructorInitialization:
4039 OS << "constructor initialization";
4040 break;
4041
4042 case SK_ZeroInitialization:
4043 OS << "zero initialization";
4044 break;
4045
4046 case SK_CAssignment:
4047 OS << "C assignment";
4048 break;
4049
4050 case SK_StringInit:
4051 OS << "string initialization";
4052 break;
4053 }
4054 }
4055}
4056
4057void InitializationSequence::dump() const {
4058 dump(llvm::errs());
4059}
4060
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004061//===----------------------------------------------------------------------===//
4062// Initialization helper functions
4063//===----------------------------------------------------------------------===//
4064Sema::OwningExprResult
4065Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4066 SourceLocation EqualLoc,
4067 OwningExprResult Init) {
4068 if (Init.isInvalid())
4069 return ExprError();
4070
4071 Expr *InitE = (Expr *)Init.get();
4072 assert(InitE && "No initialization expression?");
4073
4074 if (EqualLoc.isInvalid())
4075 EqualLoc = InitE->getLocStart();
4076
4077 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4078 EqualLoc);
4079 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4080 Init.release();
4081 return Seq.Perform(*this, Entity, Kind,
4082 MultiExprArg(*this, (void**)&InitE, 1));
4083}