blob: 981d5831b0c06a60db3573b12c3c3ffa12d093bf [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 Kremenek709210f2010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, 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 Kremenek709210f2010-04-13 23:39:13 +0000394 ILE->updateInit(SemaRef.Context, 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)
Chris Lattnere12a7792010-04-20 05:19:10 +0000889 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman2ef13e52009-08-10 23:49:36 +0000890 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);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001357 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1358 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001359 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1360 ReplacementField->getDeclContext()->getLookupContext()
1361 ->Equals(RT->getDecl())) {
1362 SemaRef.Diag(D->getFieldLoc(),
1363 diag::err_field_designator_unknown_suggest)
1364 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001365 << FixItHint::CreateReplacement(D->getFieldLoc(),
1366 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001367 SemaRef.Diag(ReplacementField->getLocation(),
1368 diag::note_previous_decl)
1369 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001370 } else {
1371 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1372 << FieldName << CurrentObjectType;
1373 ++Index;
1374 return true;
1375 }
1376 } else if (!KnownField) {
1377 // Determine whether we found a field at all.
1378 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1379 }
1380
1381 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001382 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001383 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001384 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001385 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001386 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001387 ++Index;
1388 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001389 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001390
1391 if (!KnownField &&
1392 cast<RecordDecl>((ReplacementField)->getDeclContext())
1393 ->isAnonymousStructOrUnion()) {
1394 // Handle an field designator that refers to a member of an
1395 // anonymous struct or union.
1396 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1397 ReplacementField,
1398 Field, FieldIndex);
1399 D = DIE->getDesignator(DesigIdx);
1400 } else if (!KnownField) {
1401 // The replacement field comes from typo correction; find it
1402 // in the list of fields.
1403 FieldIndex = 0;
1404 Field = RT->getDecl()->field_begin();
1405 for (; Field != FieldEnd; ++Field) {
1406 if (Field->isUnnamedBitfield())
1407 continue;
1408
1409 if (ReplacementField == *Field ||
1410 Field->getIdentifier() == ReplacementField->getIdentifier())
1411 break;
1412
1413 ++FieldIndex;
1414 }
1415 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001416 } else if (!KnownField &&
1417 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001418 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001419 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1420 Field, FieldIndex);
1421 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001422 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001423
1424 // All of the fields of a union are located at the same place in
1425 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001426 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001427 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001428 StructuredList->setInitializedFieldInUnion(*Field);
1429 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001430
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001431 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001432 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Douglas Gregor4c678342009-01-28 21:54:33 +00001434 // Make sure that our non-designated initializer list has space
1435 // for a subobject corresponding to this field.
1436 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001437 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001438
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001439 // This designator names a flexible array member.
1440 if (Field->getType()->isIncompleteArrayType()) {
1441 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001442 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001443 // We can't designate an object within the flexible array
1444 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001445 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001446 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001447 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001448 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001449 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001450 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001451 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001452 << *Field;
1453 Invalid = true;
1454 }
1455
1456 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1457 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001458 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 diag::err_flexible_array_init_needs_braces)
1460 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001461 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001462 << *Field;
1463 Invalid = true;
1464 }
1465
1466 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001467 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001468 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001469 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001470 diag::err_flexible_array_init_nonempty)
1471 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001472 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001473 << *Field;
1474 Invalid = true;
1475 }
1476
1477 if (Invalid) {
1478 ++Index;
1479 return true;
1480 }
1481
1482 // Initialize the array.
1483 bool prevHadError = hadError;
1484 unsigned newStructuredIndex = FieldIndex;
1485 unsigned OldIndex = Index;
1486 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001487
1488 InitializedEntity MemberEntity =
1489 InitializedEntity::InitializeMember(*Field, &Entity);
1490 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001492
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001493 IList->setInit(OldIndex, DIE);
1494 if (hadError && !prevHadError) {
1495 ++Field;
1496 ++FieldIndex;
1497 if (NextField)
1498 *NextField = Field;
1499 StructuredIndex = FieldIndex;
1500 return true;
1501 }
1502 } else {
1503 // Recurse to check later designated subobjects.
1504 QualType FieldType = (*Field)->getType();
1505 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001506
1507 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001508 InitializedEntity::InitializeMember(*Field, &Entity);
1509 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001510 FieldType, 0, 0, Index,
1511 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001512 true, false))
1513 return true;
1514 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001515
1516 // Find the position of the next field to be initialized in this
1517 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001518 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001519 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001520
1521 // If this the first designator, our caller will continue checking
1522 // the rest of this struct/class/union subobject.
1523 if (IsFirstDesignator) {
1524 if (NextField)
1525 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001526 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 return false;
1528 }
1529
Douglas Gregor34e79462009-01-28 23:36:17 +00001530 if (!FinishSubobjectInit)
1531 return false;
1532
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001533 // We've already initialized something in the union; we're done.
1534 if (RT->getDecl()->isUnion())
1535 return hadError;
1536
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 // Check the remaining fields within this class/struct/union subobject.
1538 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001539
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001540 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001541 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001542 return hadError && !prevHadError;
1543 }
1544
1545 // C99 6.7.8p6:
1546 //
1547 // If a designator has the form
1548 //
1549 // [ constant-expression ]
1550 //
1551 // then the current object (defined below) shall have array
1552 // type and the expression shall be an integer constant
1553 // expression. If the array is of unknown size, any
1554 // nonnegative value is valid.
1555 //
1556 // Additionally, cope with the GNU extension that permits
1557 // designators of the form
1558 //
1559 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001560 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001562 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563 << CurrentObjectType;
1564 ++Index;
1565 return true;
1566 }
1567
1568 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001569 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1570 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001572 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001573 DesignatedEndIndex = DesignatedStartIndex;
1574 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001575 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001576
Mike Stump1eb44332009-09-09 15:08:12 +00001577
1578 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001579 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001580 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001581 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001582 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001583
Chris Lattner3bf68932009-04-25 21:59:05 +00001584 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001585 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001586 }
1587
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001588 if (isa<ConstantArrayType>(AT)) {
1589 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001590 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1591 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1592 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1593 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1594 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001595 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001596 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001597 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001598 << IndexExpr->getSourceRange();
1599 ++Index;
1600 return true;
1601 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001602 } else {
1603 // Make sure the bit-widths and signedness match.
1604 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1605 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001606 else if (DesignatedStartIndex.getBitWidth() <
1607 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001608 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1609 DesignatedStartIndex.setIsUnsigned(true);
1610 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001611 }
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Douglas Gregor4c678342009-01-28 21:54:33 +00001613 // Make sure that our non-designated initializer list has space
1614 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001615 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001616 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001617 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001618
Douglas Gregor34e79462009-01-28 23:36:17 +00001619 // Repeatedly perform subobject initializations in the range
1620 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001621
Douglas Gregor34e79462009-01-28 23:36:17 +00001622 // Move to the next designator
1623 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1624 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001625
1626 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001627 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001628
Douglas Gregor34e79462009-01-28 23:36:17 +00001629 while (DesignatedStartIndex <= DesignatedEndIndex) {
1630 // Recurse to check later designated subobjects.
1631 QualType ElementType = AT->getElementType();
1632 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001633
1634 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001635 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001636 ElementType, 0, 0, Index,
1637 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001638 (DesignatedStartIndex == DesignatedEndIndex),
1639 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001640 return true;
1641
1642 // Move to the next index in the array that we'll be initializing.
1643 ++DesignatedStartIndex;
1644 ElementIndex = DesignatedStartIndex.getZExtValue();
1645 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001646
1647 // If this the first designator, our caller will continue checking
1648 // the rest of this array subobject.
1649 if (IsFirstDesignator) {
1650 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001651 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001652 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001653 return false;
1654 }
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Douglas Gregor34e79462009-01-28 23:36:17 +00001656 if (!FinishSubobjectInit)
1657 return false;
1658
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001659 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001660 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001661 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001662 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001663 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001664 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001665}
1666
Douglas Gregor4c678342009-01-28 21:54:33 +00001667// Get the structured initializer list for a subobject of type
1668// @p CurrentObjectType.
1669InitListExpr *
1670InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1671 QualType CurrentObjectType,
1672 InitListExpr *StructuredList,
1673 unsigned StructuredIndex,
1674 SourceRange InitRange) {
1675 Expr *ExistingInit = 0;
1676 if (!StructuredList)
1677 ExistingInit = SyntacticToSemantic[IList];
1678 else if (StructuredIndex < StructuredList->getNumInits())
1679 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Douglas Gregor4c678342009-01-28 21:54:33 +00001681 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1682 return Result;
1683
1684 if (ExistingInit) {
1685 // We are creating an initializer list that initializes the
1686 // subobjects of the current object, but there was already an
1687 // initialization that completely initialized the current
1688 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001689 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001690 // struct X { int a, b; };
1691 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001692 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001693 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1694 // designated initializer re-initializes the whole
1695 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001696 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001697 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001698 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001699 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001700 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001701 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001702 << ExistingInit->getSourceRange();
1703 }
1704
Mike Stump1eb44332009-09-09 15:08:12 +00001705 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001706 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1707 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001708 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001709
Douglas Gregor2c792812010-02-09 00:50:06 +00001710 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001711
Douglas Gregorfa219202009-03-20 23:58:33 +00001712 // Pre-allocate storage for the structured initializer list.
1713 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001714 unsigned NumInits = 0;
1715 if (!StructuredList)
1716 NumInits = IList->getNumInits();
1717 else if (Index < IList->getNumInits()) {
1718 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1719 NumInits = SubList->getNumInits();
1720 }
1721
Mike Stump1eb44332009-09-09 15:08:12 +00001722 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001723 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1724 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1725 NumElements = CAType->getSize().getZExtValue();
1726 // Simple heuristic so that we don't allocate a very large
1727 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001728 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001729 NumElements = 0;
1730 }
John McCall183700f2009-09-21 23:43:11 +00001731 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001732 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001733 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001734 RecordDecl *RDecl = RType->getDecl();
1735 if (RDecl->isUnion())
1736 NumElements = 1;
1737 else
Mike Stump1eb44332009-09-09 15:08:12 +00001738 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001739 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001740 }
1741
Douglas Gregor08457732009-03-21 18:13:52 +00001742 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001743 NumElements = IList->getNumInits();
1744
Ted Kremenek709210f2010-04-13 23:39:13 +00001745 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001746
Douglas Gregor4c678342009-01-28 21:54:33 +00001747 // Link this new initializer list into the structured initializer
1748 // lists.
1749 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001750 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001751 else {
1752 Result->setSyntacticForm(IList);
1753 SyntacticToSemantic[IList] = Result;
1754 }
1755
1756 return Result;
1757}
1758
1759/// Update the initializer at index @p StructuredIndex within the
1760/// structured initializer list to the value @p expr.
1761void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1762 unsigned &StructuredIndex,
1763 Expr *expr) {
1764 // No structured initializer list to update
1765 if (!StructuredList)
1766 return;
1767
Ted Kremenek709210f2010-04-13 23:39:13 +00001768 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1769 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001770 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001771 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001772 diag::warn_initializer_overrides)
1773 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001774 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001775 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001776 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001777 << PrevInit->getSourceRange();
1778 }
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Douglas Gregor4c678342009-01-28 21:54:33 +00001780 ++StructuredIndex;
1781}
1782
Douglas Gregor05c13a32009-01-22 00:58:24 +00001783/// Check that the given Index expression is a valid array designator
1784/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001785/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001786/// and produces a reasonable diagnostic if there is a
1787/// failure. Returns true if there was an error, false otherwise. If
1788/// everything went okay, Value will receive the value of the constant
1789/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001790static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001791CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001792 SourceLocation Loc = Index->getSourceRange().getBegin();
1793
1794 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001795 if (S.VerifyIntegerConstantExpression(Index, &Value))
1796 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001797
Chris Lattner3bf68932009-04-25 21:59:05 +00001798 if (Value.isSigned() && Value.isNegative())
1799 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001800 << Value.toString(10) << Index->getSourceRange();
1801
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001802 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001803 return false;
1804}
1805
1806Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1807 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001808 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001809 OwningExprResult Init) {
1810 typedef DesignatedInitExpr::Designator ASTDesignator;
1811
1812 bool Invalid = false;
1813 llvm::SmallVector<ASTDesignator, 32> Designators;
1814 llvm::SmallVector<Expr *, 32> InitExpressions;
1815
1816 // Build designators and check array designator expressions.
1817 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1818 const Designator &D = Desig.getDesignator(Idx);
1819 switch (D.getKind()) {
1820 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001821 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001822 D.getFieldLoc()));
1823 break;
1824
1825 case Designator::ArrayDesignator: {
1826 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1827 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001828 if (!Index->isTypeDependent() &&
1829 !Index->isValueDependent() &&
1830 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001831 Invalid = true;
1832 else {
1833 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001834 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001835 D.getRBracketLoc()));
1836 InitExpressions.push_back(Index);
1837 }
1838 break;
1839 }
1840
1841 case Designator::ArrayRangeDesignator: {
1842 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1843 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1844 llvm::APSInt StartValue;
1845 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001846 bool StartDependent = StartIndex->isTypeDependent() ||
1847 StartIndex->isValueDependent();
1848 bool EndDependent = EndIndex->isTypeDependent() ||
1849 EndIndex->isValueDependent();
1850 if ((!StartDependent &&
1851 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1852 (!EndDependent &&
1853 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001854 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001855 else {
1856 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001857 if (StartDependent || EndDependent) {
1858 // Nothing to compute.
1859 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001860 EndValue.extend(StartValue.getBitWidth());
1861 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1862 StartValue.extend(EndValue.getBitWidth());
1863
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001864 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001865 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001866 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001867 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1868 Invalid = true;
1869 } else {
1870 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001871 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001872 D.getEllipsisLoc(),
1873 D.getRBracketLoc()));
1874 InitExpressions.push_back(StartIndex);
1875 InitExpressions.push_back(EndIndex);
1876 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001877 }
1878 break;
1879 }
1880 }
1881 }
1882
1883 if (Invalid || Init.isInvalid())
1884 return ExprError();
1885
1886 // Clear out the expressions within the designation.
1887 Desig.ClearExprs(*this);
1888
1889 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001890 = DesignatedInitExpr::Create(Context,
1891 Designators.data(), Designators.size(),
1892 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001893 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001894 return Owned(DIE);
1895}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001896
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001897bool Sema::CheckInitList(const InitializedEntity &Entity,
1898 InitListExpr *&InitList, QualType &DeclType) {
1899 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001900 if (!CheckInitList.HadError())
1901 InitList = CheckInitList.getFullyStructuredList();
1902
1903 return CheckInitList.HadError();
1904}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001905
Douglas Gregor20093b42009-12-09 23:02:17 +00001906//===----------------------------------------------------------------------===//
1907// Initialization entity
1908//===----------------------------------------------------------------------===//
1909
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001910InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1911 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001912 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001913{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001914 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1915 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001916 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001917 } else {
1918 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001919 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001920 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001921}
1922
1923InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1924 CXXBaseSpecifier *Base)
1925{
1926 InitializedEntity Result;
1927 Result.Kind = EK_Base;
1928 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001929 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001930 return Result;
1931}
1932
Douglas Gregor99a2e602009-12-16 01:38:02 +00001933DeclarationName InitializedEntity::getName() const {
1934 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001935 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001936 if (!VariableOrMember)
1937 return DeclarationName();
1938 // Fall through
1939
1940 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001941 case EK_Member:
1942 return VariableOrMember->getDeclName();
1943
1944 case EK_Result:
1945 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001946 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001947 case EK_Temporary:
1948 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001949 case EK_ArrayElement:
1950 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001951 return DeclarationName();
1952 }
1953
1954 // Silence GCC warning
1955 return DeclarationName();
1956}
1957
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001958DeclaratorDecl *InitializedEntity::getDecl() const {
1959 switch (getKind()) {
1960 case EK_Variable:
1961 case EK_Parameter:
1962 case EK_Member:
1963 return VariableOrMember;
1964
1965 case EK_Result:
1966 case EK_Exception:
1967 case EK_New:
1968 case EK_Temporary:
1969 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001970 case EK_ArrayElement:
1971 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001972 return 0;
1973 }
1974
1975 // Silence GCC warning
1976 return 0;
1977}
1978
Douglas Gregor20093b42009-12-09 23:02:17 +00001979//===----------------------------------------------------------------------===//
1980// Initialization sequence
1981//===----------------------------------------------------------------------===//
1982
1983void InitializationSequence::Step::Destroy() {
1984 switch (Kind) {
1985 case SK_ResolveAddressOfOverloadedFunction:
1986 case SK_CastDerivedToBaseRValue:
1987 case SK_CastDerivedToBaseLValue:
1988 case SK_BindReference:
1989 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00001990 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00001991 case SK_UserConversion:
1992 case SK_QualificationConversionRValue:
1993 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001994 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001995 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001996 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001997 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001998 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001999 break;
2000
2001 case SK_ConversionSequence:
2002 delete ICS;
2003 }
2004}
2005
Douglas Gregorb70cf442010-03-26 20:14:36 +00002006bool InitializationSequence::isDirectReferenceBinding() const {
2007 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2008}
2009
2010bool InitializationSequence::isAmbiguous() const {
2011 if (getKind() != FailedSequence)
2012 return false;
2013
2014 switch (getFailureKind()) {
2015 case FK_TooManyInitsForReference:
2016 case FK_ArrayNeedsInitList:
2017 case FK_ArrayNeedsInitListOrStringLiteral:
2018 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2019 case FK_NonConstLValueReferenceBindingToTemporary:
2020 case FK_NonConstLValueReferenceBindingToUnrelated:
2021 case FK_RValueReferenceBindingToLValue:
2022 case FK_ReferenceInitDropsQualifiers:
2023 case FK_ReferenceInitFailed:
2024 case FK_ConversionFailed:
2025 case FK_TooManyInitsForScalar:
2026 case FK_ReferenceBindingToInitList:
2027 case FK_InitListBadDestinationType:
2028 case FK_DefaultInitOfConst:
2029 return false;
2030
2031 case FK_ReferenceInitOverloadFailed:
2032 case FK_UserConversionOverloadFailed:
2033 case FK_ConstructorOverloadFailed:
2034 return FailedOverloadResult == OR_Ambiguous;
2035 }
2036
2037 return false;
2038}
2039
Douglas Gregord6e44a32010-04-16 22:09:46 +00002040bool InitializationSequence::isConstructorInitialization() const {
2041 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2042}
2043
Douglas Gregor20093b42009-12-09 23:02:17 +00002044void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002045 FunctionDecl *Function,
2046 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002047 Step S;
2048 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2049 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002050 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002051 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002052 Steps.push_back(S);
2053}
2054
2055void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2056 bool IsLValue) {
2057 Step S;
2058 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2059 S.Type = BaseType;
2060 Steps.push_back(S);
2061}
2062
2063void InitializationSequence::AddReferenceBindingStep(QualType T,
2064 bool BindingTemporary) {
2065 Step S;
2066 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2067 S.Type = T;
2068 Steps.push_back(S);
2069}
2070
Douglas Gregor523d46a2010-04-18 07:40:54 +00002071void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2072 Step S;
2073 S.Kind = SK_ExtraneousCopyToTemporary;
2074 S.Type = T;
2075 Steps.push_back(S);
2076}
2077
Eli Friedman03981012009-12-11 02:42:07 +00002078void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002079 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002080 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002081 Step S;
2082 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002083 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002084 S.Function.Function = Function;
2085 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002086 Steps.push_back(S);
2087}
2088
2089void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2090 bool IsLValue) {
2091 Step S;
2092 S.Kind = IsLValue? SK_QualificationConversionLValue
2093 : SK_QualificationConversionRValue;
2094 S.Type = Ty;
2095 Steps.push_back(S);
2096}
2097
2098void InitializationSequence::AddConversionSequenceStep(
2099 const ImplicitConversionSequence &ICS,
2100 QualType T) {
2101 Step S;
2102 S.Kind = SK_ConversionSequence;
2103 S.Type = T;
2104 S.ICS = new ImplicitConversionSequence(ICS);
2105 Steps.push_back(S);
2106}
2107
Douglas Gregord87b61f2009-12-10 17:56:55 +00002108void InitializationSequence::AddListInitializationStep(QualType T) {
2109 Step S;
2110 S.Kind = SK_ListInitialization;
2111 S.Type = T;
2112 Steps.push_back(S);
2113}
2114
Douglas Gregor51c56d62009-12-14 20:49:26 +00002115void
2116InitializationSequence::AddConstructorInitializationStep(
2117 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002118 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002119 QualType T) {
2120 Step S;
2121 S.Kind = SK_ConstructorInitialization;
2122 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002123 S.Function.Function = Constructor;
2124 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002125 Steps.push_back(S);
2126}
2127
Douglas Gregor71d17402009-12-15 00:01:57 +00002128void InitializationSequence::AddZeroInitializationStep(QualType T) {
2129 Step S;
2130 S.Kind = SK_ZeroInitialization;
2131 S.Type = T;
2132 Steps.push_back(S);
2133}
2134
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002135void InitializationSequence::AddCAssignmentStep(QualType T) {
2136 Step S;
2137 S.Kind = SK_CAssignment;
2138 S.Type = T;
2139 Steps.push_back(S);
2140}
2141
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002142void InitializationSequence::AddStringInitStep(QualType T) {
2143 Step S;
2144 S.Kind = SK_StringInit;
2145 S.Type = T;
2146 Steps.push_back(S);
2147}
2148
Douglas Gregor20093b42009-12-09 23:02:17 +00002149void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2150 OverloadingResult Result) {
2151 SequenceKind = FailedSequence;
2152 this->Failure = Failure;
2153 this->FailedOverloadResult = Result;
2154}
2155
2156//===----------------------------------------------------------------------===//
2157// Attempt initialization
2158//===----------------------------------------------------------------------===//
2159
2160/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002161static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002162 const InitializedEntity &Entity,
2163 const InitializationKind &Kind,
2164 InitListExpr *InitList,
2165 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002166 // FIXME: We only perform rudimentary checking of list
2167 // initializations at this point, then assume that any list
2168 // initialization of an array, aggregate, or scalar will be
2169 // well-formed. We we actually "perform" list initialization, we'll
2170 // do all of the necessary checking. C++0x initializer lists will
2171 // force us to perform more checking here.
2172 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2173
Douglas Gregord6542d82009-12-22 15:35:07 +00002174 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002175
2176 // C++ [dcl.init]p13:
2177 // If T is a scalar type, then a declaration of the form
2178 //
2179 // T x = { a };
2180 //
2181 // is equivalent to
2182 //
2183 // T x = a;
2184 if (DestType->isScalarType()) {
2185 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2186 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2187 return;
2188 }
2189
2190 // Assume scalar initialization from a single value works.
2191 } else if (DestType->isAggregateType()) {
2192 // Assume aggregate initialization works.
2193 } else if (DestType->isVectorType()) {
2194 // Assume vector initialization works.
2195 } else if (DestType->isReferenceType()) {
2196 // FIXME: C++0x defines behavior for this.
2197 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2198 return;
2199 } else if (DestType->isRecordType()) {
2200 // FIXME: C++0x defines behavior for this
2201 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2202 }
2203
2204 // Add a general "list initialization" step.
2205 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002206}
2207
2208/// \brief Try a reference initialization that involves calling a conversion
2209/// function.
2210///
2211/// FIXME: look intos DRs 656, 896
2212static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2213 const InitializedEntity &Entity,
2214 const InitializationKind &Kind,
2215 Expr *Initializer,
2216 bool AllowRValues,
2217 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002218 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002219 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2220 QualType T1 = cv1T1.getUnqualifiedType();
2221 QualType cv2T2 = Initializer->getType();
2222 QualType T2 = cv2T2.getUnqualifiedType();
2223
2224 bool DerivedToBase;
2225 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2226 T1, T2, DerivedToBase) &&
2227 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002228 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002229
2230 // Build the candidate set directly in the initialization sequence
2231 // structure, so that it will persist if we fail.
2232 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2233 CandidateSet.clear();
2234
2235 // Determine whether we are allowed to call explicit constructors or
2236 // explicit conversion operators.
2237 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2238
2239 const RecordType *T1RecordType = 0;
2240 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2241 // The type we're converting to is a class type. Enumerate its constructors
2242 // to see if there is a suitable conversion.
2243 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2244
2245 DeclarationName ConstructorName
2246 = S.Context.DeclarationNames.getCXXConstructorName(
2247 S.Context.getCanonicalType(T1).getUnqualifiedType());
2248 DeclContext::lookup_iterator Con, ConEnd;
2249 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2250 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002251 NamedDecl *D = *Con;
2252 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2253
Douglas Gregor20093b42009-12-09 23:02:17 +00002254 // Find the constructor (which may be a template).
2255 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002256 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002257 if (ConstructorTmpl)
2258 Constructor = cast<CXXConstructorDecl>(
2259 ConstructorTmpl->getTemplatedDecl());
2260 else
John McCall9aa472c2010-03-19 07:35:19 +00002261 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002262
2263 if (!Constructor->isInvalidDecl() &&
2264 Constructor->isConvertingConstructor(AllowExplicit)) {
2265 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002266 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002267 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002268 &Initializer, 1, CandidateSet);
2269 else
John McCall9aa472c2010-03-19 07:35:19 +00002270 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002271 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002272 }
2273 }
2274 }
2275
2276 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2277 // The type we're converting from is a class type, enumerate its conversion
2278 // functions.
2279 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2280
2281 // Determine the type we are converting to. If we are allowed to
2282 // convert to an rvalue, take the type that the destination type
2283 // refers to.
2284 QualType ToType = AllowRValues? cv1T1 : DestType;
2285
John McCalleec51cf2010-01-20 00:46:10 +00002286 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002287 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002288 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2289 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002290 NamedDecl *D = *I;
2291 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2292 if (isa<UsingShadowDecl>(D))
2293 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2294
2295 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2296 CXXConversionDecl *Conv;
2297 if (ConvTemplate)
2298 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2299 else
2300 Conv = cast<CXXConversionDecl>(*I);
2301
2302 // If the conversion function doesn't return a reference type,
2303 // it can't be considered for this conversion unless we're allowed to
2304 // consider rvalues.
2305 // FIXME: Do we need to make sure that we only consider conversion
2306 // candidates with reference-compatible results? That might be needed to
2307 // break recursion.
2308 if ((AllowExplicit || !Conv->isExplicit()) &&
2309 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2310 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002311 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002312 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002313 ToType, CandidateSet);
2314 else
John McCall9aa472c2010-03-19 07:35:19 +00002315 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002316 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002317 }
2318 }
2319 }
2320
2321 SourceLocation DeclLoc = Initializer->getLocStart();
2322
2323 // Perform overload resolution. If it fails, return the failed result.
2324 OverloadCandidateSet::iterator Best;
2325 if (OverloadingResult Result
2326 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2327 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002328
Douglas Gregor20093b42009-12-09 23:02:17 +00002329 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002330
2331 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002332 if (isa<CXXConversionDecl>(Function))
2333 T2 = Function->getResultType();
2334 else
2335 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002336
2337 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002338 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
John McCallb13b7372010-02-01 03:16:54 +00002339 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002340
2341 // Determine whether we need to perform derived-to-base or
2342 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002343 bool NewDerivedToBase = false;
2344 Sema::ReferenceCompareResult NewRefRelationship
2345 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2346 NewDerivedToBase);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002347 if (NewRefRelationship == Sema::Ref_Incompatible) {
2348 // If the type we've converted to is not reference-related to the
2349 // type we're looking for, then there is another conversion step
2350 // we need to perform to produce a temporary of the right type
2351 // that we'll be binding to.
2352 ImplicitConversionSequence ICS;
2353 ICS.setStandard();
2354 ICS.Standard = Best->FinalConversion;
2355 T2 = ICS.Standard.getToType(2);
2356 Sequence.AddConversionSequenceStep(ICS, T2);
2357 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002358 Sequence.AddDerivedToBaseCastStep(
2359 S.Context.getQualifiedType(T1,
2360 T2.getNonReferenceType().getQualifiers()),
2361 /*isLValue=*/true);
2362
2363 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2364 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2365
2366 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2367 return OR_Success;
2368}
2369
2370/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2371static void TryReferenceInitialization(Sema &S,
2372 const InitializedEntity &Entity,
2373 const InitializationKind &Kind,
2374 Expr *Initializer,
2375 InitializationSequence &Sequence) {
2376 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2377
Douglas Gregord6542d82009-12-22 15:35:07 +00002378 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002379 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002380 Qualifiers T1Quals;
2381 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002382 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002383 Qualifiers T2Quals;
2384 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002385 SourceLocation DeclLoc = Initializer->getLocStart();
2386
2387 // If the initializer is the address of an overloaded function, try
2388 // to resolve the overloaded function. If all goes well, T2 is the
2389 // type of the resulting function.
2390 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002391 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002392 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2393 T1,
John McCall6bb80172010-03-30 21:47:33 +00002394 false,
2395 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002396 if (!Fn) {
2397 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2398 return;
2399 }
2400
John McCall6bb80172010-03-30 21:47:33 +00002401 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002402 cv2T2 = Fn->getType();
2403 T2 = cv2T2.getUnqualifiedType();
2404 }
2405
Douglas Gregor20093b42009-12-09 23:02:17 +00002406 // Compute some basic properties of the types and the initializer.
2407 bool isLValueRef = DestType->isLValueReferenceType();
2408 bool isRValueRef = !isLValueRef;
2409 bool DerivedToBase = false;
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002410 Expr::isLvalueResult InitLvalue = Initializer->isLvalue(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 Sema::ReferenceCompareResult RefRelationship
2412 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2413
2414 // C++0x [dcl.init.ref]p5:
2415 // A reference to type "cv1 T1" is initialized by an expression of type
2416 // "cv2 T2" as follows:
2417 //
2418 // - If the reference is an lvalue reference and the initializer
2419 // expression
2420 OverloadingResult ConvOvlResult = OR_Success;
2421 if (isLValueRef) {
2422 if (InitLvalue == Expr::LV_Valid &&
2423 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2424 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2425 // reference-compatible with "cv2 T2," or
2426 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002427 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002428 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002429 // can occur. However, we do pay attention to whether it is a bit-field
2430 // to decide whether we're actually binding to a temporary created from
2431 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002432 if (DerivedToBase)
2433 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002434 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002435 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002436 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002437 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002438 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002439 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002440 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002441 return;
2442 }
2443
2444 // - has a class type (i.e., T2 is a class type), where T1 is not
2445 // reference-related to T2, and can be implicitly converted to an
2446 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2447 // with "cv3 T3" (this conversion is selected by enumerating the
2448 // applicable conversion functions (13.3.1.6) and choosing the best
2449 // one through overload resolution (13.3)),
2450 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2451 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2452 Initializer,
2453 /*AllowRValues=*/false,
2454 Sequence);
2455 if (ConvOvlResult == OR_Success)
2456 return;
John McCall1d318332010-01-12 00:44:57 +00002457 if (ConvOvlResult != OR_No_Viable_Function) {
2458 Sequence.SetOverloadFailure(
2459 InitializationSequence::FK_ReferenceInitOverloadFailed,
2460 ConvOvlResult);
2461 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002462 }
2463 }
2464
2465 // - Otherwise, the reference shall be an lvalue reference to a
2466 // non-volatile const type (i.e., cv1 shall be const), or the reference
2467 // shall be an rvalue reference and the initializer expression shall
2468 // be an rvalue.
Douglas Gregoref06e242010-01-29 19:39:15 +00002469 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2471 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2472 Sequence.SetOverloadFailure(
2473 InitializationSequence::FK_ReferenceInitOverloadFailed,
2474 ConvOvlResult);
2475 else if (isLValueRef)
2476 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2477 ? (RefRelationship == Sema::Ref_Related
2478 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2479 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2480 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2481 else
2482 Sequence.SetFailed(
2483 InitializationSequence::FK_RValueReferenceBindingToLValue);
2484
2485 return;
2486 }
2487
2488 // - If T1 and T2 are class types and
2489 if (T1->isRecordType() && T2->isRecordType()) {
2490 // - the initializer expression is an rvalue and "cv1 T1" is
2491 // reference-compatible with "cv2 T2", or
2492 if (InitLvalue != Expr::LV_Valid &&
2493 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002494 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2495 // compiler the freedom to perform a copy here or bind to the
2496 // object, while C++0x requires that we bind directly to the
2497 // object. Hence, we always bind to the object without making an
2498 // extra copy. However, in C++03 requires that we check for the
2499 // presence of a suitable copy constructor:
2500 //
2501 // The constructor that would be used to make the copy shall
2502 // be callable whether or not the copy is actually done.
2503 if (!S.getLangOptions().CPlusPlus0x)
2504 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2505
Douglas Gregor20093b42009-12-09 23:02:17 +00002506 if (DerivedToBase)
2507 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002508 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002509 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002510 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002511 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2512 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2513 return;
2514 }
2515
2516 // - T1 is not reference-related to T2 and the initializer expression
2517 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2518 // conversion is selected by enumerating the applicable conversion
2519 // functions (13.3.1.6) and choosing the best one through overload
2520 // resolution (13.3)),
2521 if (RefRelationship == Sema::Ref_Incompatible) {
2522 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2523 Kind, Initializer,
2524 /*AllowRValues=*/true,
2525 Sequence);
2526 if (ConvOvlResult)
2527 Sequence.SetOverloadFailure(
2528 InitializationSequence::FK_ReferenceInitOverloadFailed,
2529 ConvOvlResult);
2530
2531 return;
2532 }
2533
2534 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2535 return;
2536 }
2537
2538 // - If the initializer expression is an rvalue, with T2 an array type,
2539 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2540 // is bound to the object represented by the rvalue (see 3.10).
2541 // FIXME: How can an array type be reference-compatible with anything?
2542 // Don't we mean the element types of T1 and T2?
2543
2544 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2545 // from the initializer expression using the rules for a non-reference
2546 // copy initialization (8.5). The reference is then bound to the
2547 // temporary. [...]
2548 // Determine whether we are allowed to call explicit constructors or
2549 // explicit conversion operators.
2550 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2551 ImplicitConversionSequence ICS
2552 = S.TryImplicitConversion(Initializer, cv1T1,
2553 /*SuppressUserConversions=*/false, AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002554 /*FIXME:InOverloadResolution=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00002555
John McCall1d318332010-01-12 00:44:57 +00002556 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002557 // FIXME: Use the conversion function set stored in ICS to turn
2558 // this into an overloading ambiguity diagnostic. However, we need
2559 // to keep that set as an OverloadCandidateSet rather than as some
2560 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002561 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2562 Sequence.SetOverloadFailure(
2563 InitializationSequence::FK_ReferenceInitOverloadFailed,
2564 ConvOvlResult);
2565 else
2566 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002567 return;
2568 }
2569
2570 // [...] If T1 is reference-related to T2, cv1 must be the
2571 // same cv-qualification as, or greater cv-qualification
2572 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002573 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2574 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002575 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002576 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002577 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2578 return;
2579 }
2580
2581 // Perform the actual conversion.
2582 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2583 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2584 return;
2585}
2586
2587/// \brief Attempt character array initialization from a string literal
2588/// (C++ [dcl.init.string], C99 6.7.8).
2589static void TryStringLiteralInitialization(Sema &S,
2590 const InitializedEntity &Entity,
2591 const InitializationKind &Kind,
2592 Expr *Initializer,
2593 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002594 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002595 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002596}
2597
Douglas Gregor20093b42009-12-09 23:02:17 +00002598/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2599/// enumerates the constructors of the initialized entity and performs overload
2600/// resolution to select the best.
2601static void TryConstructorInitialization(Sema &S,
2602 const InitializedEntity &Entity,
2603 const InitializationKind &Kind,
2604 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002605 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002606 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002607 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002608
2609 // Build the candidate set directly in the initialization sequence
2610 // structure, so that it will persist if we fail.
2611 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2612 CandidateSet.clear();
2613
2614 // Determine whether we are allowed to call explicit constructors or
2615 // explicit conversion operators.
2616 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2617 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002618 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002619
2620 // The type we're converting to is a class type. Enumerate its constructors
2621 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002622 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2623 assert(DestRecordType && "Constructor initialization requires record type");
2624 CXXRecordDecl *DestRecordDecl
2625 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2626
2627 DeclarationName ConstructorName
2628 = S.Context.DeclarationNames.getCXXConstructorName(
2629 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2630 DeclContext::lookup_iterator Con, ConEnd;
2631 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2632 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002633 NamedDecl *D = *Con;
2634 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2635
Douglas Gregor51c56d62009-12-14 20:49:26 +00002636 // Find the constructor (which may be a template).
2637 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002638 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002639 if (ConstructorTmpl)
2640 Constructor = cast<CXXConstructorDecl>(
2641 ConstructorTmpl->getTemplatedDecl());
2642 else
John McCall9aa472c2010-03-19 07:35:19 +00002643 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002644
2645 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002646 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002647 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002648 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002649 /*ExplicitArgs*/ 0,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002650 Args, NumArgs, CandidateSet);
2651 else
John McCall9aa472c2010-03-19 07:35:19 +00002652 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002653 Args, NumArgs, CandidateSet);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002654 }
2655 }
2656
2657 SourceLocation DeclLoc = Kind.getLocation();
2658
2659 // Perform overload resolution. If it fails, return the failed result.
2660 OverloadCandidateSet::iterator Best;
2661 if (OverloadingResult Result
2662 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2663 Sequence.SetOverloadFailure(
2664 InitializationSequence::FK_ConstructorOverloadFailed,
2665 Result);
2666 return;
2667 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002668
2669 // C++0x [dcl.init]p6:
2670 // If a program calls for the default initialization of an object
2671 // of a const-qualified type T, T shall be a class type with a
2672 // user-provided default constructor.
2673 if (Kind.getKind() == InitializationKind::IK_Default &&
2674 Entity.getType().isConstQualified() &&
2675 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2676 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2677 return;
2678 }
2679
Douglas Gregor51c56d62009-12-14 20:49:26 +00002680 // Add the constructor initialization step. Any cv-qualification conversion is
2681 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002682 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002683 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002684 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002685 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002686}
2687
Douglas Gregor71d17402009-12-15 00:01:57 +00002688/// \brief Attempt value initialization (C++ [dcl.init]p7).
2689static void TryValueInitialization(Sema &S,
2690 const InitializedEntity &Entity,
2691 const InitializationKind &Kind,
2692 InitializationSequence &Sequence) {
2693 // C++ [dcl.init]p5:
2694 //
2695 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002696 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002697
2698 // -- if T is an array type, then each element is value-initialized;
2699 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2700 T = AT->getElementType();
2701
2702 if (const RecordType *RT = T->getAs<RecordType>()) {
2703 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2704 // -- if T is a class type (clause 9) with a user-declared
2705 // constructor (12.1), then the default constructor for T is
2706 // called (and the initialization is ill-formed if T has no
2707 // accessible default constructor);
2708 //
2709 // FIXME: we really want to refer to a single subobject of the array,
2710 // but Entity doesn't have a way to capture that (yet).
2711 if (ClassDecl->hasUserDeclaredConstructor())
2712 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2713
Douglas Gregor16006c92009-12-16 18:50:27 +00002714 // -- if T is a (possibly cv-qualified) non-union class type
2715 // without a user-provided constructor, then the object is
2716 // zero-initialized and, if T’s implicitly-declared default
2717 // constructor is non-trivial, that constructor is called.
2718 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2719 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2720 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002721 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002722 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2723 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002724 }
2725 }
2726
Douglas Gregord6542d82009-12-22 15:35:07 +00002727 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002728 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2729}
2730
Douglas Gregor99a2e602009-12-16 01:38:02 +00002731/// \brief Attempt default initialization (C++ [dcl.init]p6).
2732static void TryDefaultInitialization(Sema &S,
2733 const InitializedEntity &Entity,
2734 const InitializationKind &Kind,
2735 InitializationSequence &Sequence) {
2736 assert(Kind.getKind() == InitializationKind::IK_Default);
2737
2738 // C++ [dcl.init]p6:
2739 // To default-initialize an object of type T means:
2740 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002741 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002742 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2743 DestType = Array->getElementType();
2744
2745 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2746 // constructor for T is called (and the initialization is ill-formed if
2747 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002748 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002749 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2750 Sequence);
2751 }
2752
2753 // - otherwise, no initialization is performed.
2754 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2755
2756 // If a program calls for the default initialization of an object of
2757 // a const-qualified type T, T shall be a class type with a user-provided
2758 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002759 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002760 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2761}
2762
Douglas Gregor20093b42009-12-09 23:02:17 +00002763/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2764/// which enumerates all conversion functions and performs overload resolution
2765/// to select the best.
2766static void TryUserDefinedConversion(Sema &S,
2767 const InitializedEntity &Entity,
2768 const InitializationKind &Kind,
2769 Expr *Initializer,
2770 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002771 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2772
Douglas Gregord6542d82009-12-22 15:35:07 +00002773 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002774 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2775 QualType SourceType = Initializer->getType();
2776 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2777 "Must have a class type to perform a user-defined conversion");
2778
2779 // Build the candidate set directly in the initialization sequence
2780 // structure, so that it will persist if we fail.
2781 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2782 CandidateSet.clear();
2783
2784 // Determine whether we are allowed to call explicit constructors or
2785 // explicit conversion operators.
2786 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2787
2788 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2789 // The type we're converting to is a class type. Enumerate its constructors
2790 // to see if there is a suitable conversion.
2791 CXXRecordDecl *DestRecordDecl
2792 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2793
2794 DeclarationName ConstructorName
2795 = S.Context.DeclarationNames.getCXXConstructorName(
2796 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2797 DeclContext::lookup_iterator Con, ConEnd;
2798 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2799 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002800 NamedDecl *D = *Con;
2801 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2802
Douglas Gregor4a520a22009-12-14 17:27:33 +00002803 // Find the constructor (which may be a template).
2804 CXXConstructorDecl *Constructor = 0;
2805 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002806 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002807 if (ConstructorTmpl)
2808 Constructor = cast<CXXConstructorDecl>(
2809 ConstructorTmpl->getTemplatedDecl());
2810 else
John McCall9aa472c2010-03-19 07:35:19 +00002811 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002812
2813 if (!Constructor->isInvalidDecl() &&
2814 Constructor->isConvertingConstructor(AllowExplicit)) {
2815 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002816 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002817 /*ExplicitArgs*/ 0,
Douglas Gregor4a520a22009-12-14 17:27:33 +00002818 &Initializer, 1, CandidateSet);
2819 else
John McCall9aa472c2010-03-19 07:35:19 +00002820 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002821 &Initializer, 1, CandidateSet);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002822 }
2823 }
2824 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002825
2826 SourceLocation DeclLoc = Initializer->getLocStart();
2827
Douglas Gregor4a520a22009-12-14 17:27:33 +00002828 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2829 // The type we're converting from is a class type, enumerate its conversion
2830 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002831
Eli Friedman33c2da92009-12-20 22:12:03 +00002832 // We can only enumerate the conversion functions for a complete type; if
2833 // the type isn't complete, simply skip this step.
2834 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2835 CXXRecordDecl *SourceRecordDecl
2836 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002837
John McCalleec51cf2010-01-20 00:46:10 +00002838 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002839 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002840 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002841 E = Conversions->end();
2842 I != E; ++I) {
2843 NamedDecl *D = *I;
2844 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2845 if (isa<UsingShadowDecl>(D))
2846 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2847
2848 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2849 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002850 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002851 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002852 else
John McCall32daa422010-03-31 01:36:47 +00002853 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002854
2855 if (AllowExplicit || !Conv->isExplicit()) {
2856 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002857 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002858 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002859 CandidateSet);
2860 else
John McCall9aa472c2010-03-19 07:35:19 +00002861 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002862 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002863 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002864 }
2865 }
2866 }
2867
Douglas Gregor4a520a22009-12-14 17:27:33 +00002868 // Perform overload resolution. If it fails, return the failed result.
2869 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002870 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002871 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2872 Sequence.SetOverloadFailure(
2873 InitializationSequence::FK_UserConversionOverloadFailed,
2874 Result);
2875 return;
2876 }
John McCall1d318332010-01-12 00:44:57 +00002877
Douglas Gregor4a520a22009-12-14 17:27:33 +00002878 FunctionDecl *Function = Best->Function;
2879
2880 if (isa<CXXConstructorDecl>(Function)) {
2881 // Add the user-defined conversion step. Any cv-qualification conversion is
2882 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002883 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002884 return;
2885 }
2886
2887 // Add the user-defined conversion step that calls the conversion function.
2888 QualType ConvType = Function->getResultType().getNonReferenceType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002889 if (ConvType->getAs<RecordType>()) {
2890 // If we're converting to a class type, there may be an copy if
2891 // the resulting temporary object (possible to create an object of
2892 // a base class type). That copy is not a separate conversion, so
2893 // we just make a note of the actual destination type (possibly a
2894 // base class of the type returned by the conversion function) and
2895 // let the user-defined conversion step handle the conversion.
2896 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2897 return;
2898 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002899
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002900 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
2901
2902 // If the conversion following the call to the conversion function
2903 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00002904 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2905 Best->FinalConversion.Third) {
2906 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002907 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002908 ICS.Standard = Best->FinalConversion;
2909 Sequence.AddConversionSequenceStep(ICS, DestType);
2910 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002911}
2912
2913/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2914/// non-class type to another.
2915static void TryImplicitConversion(Sema &S,
2916 const InitializedEntity &Entity,
2917 const InitializationKind &Kind,
2918 Expr *Initializer,
2919 InitializationSequence &Sequence) {
2920 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002921 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002922 /*SuppressUserConversions=*/true,
2923 /*AllowExplicit=*/false,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002924 /*InOverloadResolution=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00002925
John McCall1d318332010-01-12 00:44:57 +00002926 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002927 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2928 return;
2929 }
2930
Douglas Gregord6542d82009-12-22 15:35:07 +00002931 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002932}
2933
2934InitializationSequence::InitializationSequence(Sema &S,
2935 const InitializedEntity &Entity,
2936 const InitializationKind &Kind,
2937 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002938 unsigned NumArgs)
2939 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002940 ASTContext &Context = S.Context;
2941
2942 // C++0x [dcl.init]p16:
2943 // The semantics of initializers are as follows. The destination type is
2944 // the type of the object or reference being initialized and the source
2945 // type is the type of the initializer expression. The source type is not
2946 // defined when the initializer is a braced-init-list or when it is a
2947 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002948 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002949
2950 if (DestType->isDependentType() ||
2951 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2952 SequenceKind = DependentSequence;
2953 return;
2954 }
2955
2956 QualType SourceType;
2957 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002958 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002959 Initializer = Args[0];
2960 if (!isa<InitListExpr>(Initializer))
2961 SourceType = Initializer->getType();
2962 }
2963
2964 // - If the initializer is a braced-init-list, the object is
2965 // list-initialized (8.5.4).
2966 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2967 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002968 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002969 }
2970
2971 // - If the destination type is a reference type, see 8.5.3.
2972 if (DestType->isReferenceType()) {
2973 // C++0x [dcl.init.ref]p1:
2974 // A variable declared to be a T& or T&&, that is, "reference to type T"
2975 // (8.3.2), shall be initialized by an object, or function, of type T or
2976 // by an object that can be converted into a T.
2977 // (Therefore, multiple arguments are not permitted.)
2978 if (NumArgs != 1)
2979 SetFailed(FK_TooManyInitsForReference);
2980 else
2981 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2982 return;
2983 }
2984
2985 // - If the destination type is an array of characters, an array of
2986 // char16_t, an array of char32_t, or an array of wchar_t, and the
2987 // initializer is a string literal, see 8.5.2.
2988 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2989 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2990 return;
2991 }
2992
2993 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002994 if (Kind.getKind() == InitializationKind::IK_Value ||
2995 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002996 TryValueInitialization(S, Entity, Kind, *this);
2997 return;
2998 }
2999
Douglas Gregor99a2e602009-12-16 01:38:02 +00003000 // Handle default initialization.
3001 if (Kind.getKind() == InitializationKind::IK_Default){
3002 TryDefaultInitialization(S, Entity, Kind, *this);
3003 return;
3004 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003005
Douglas Gregor20093b42009-12-09 23:02:17 +00003006 // - Otherwise, if the destination type is an array, the program is
3007 // ill-formed.
3008 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3009 if (AT->getElementType()->isAnyCharacterType())
3010 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3011 else
3012 SetFailed(FK_ArrayNeedsInitList);
3013
3014 return;
3015 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003016
3017 // Handle initialization in C
3018 if (!S.getLangOptions().CPlusPlus) {
3019 setSequenceKind(CAssignment);
3020 AddCAssignmentStep(DestType);
3021 return;
3022 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003023
3024 // - If the destination type is a (possibly cv-qualified) class type:
3025 if (DestType->isRecordType()) {
3026 // - If the initialization is direct-initialization, or if it is
3027 // copy-initialization where the cv-unqualified version of the
3028 // source type is the same class as, or a derived class of, the
3029 // class of the destination, constructors are considered. [...]
3030 if (Kind.getKind() == InitializationKind::IK_Direct ||
3031 (Kind.getKind() == InitializationKind::IK_Copy &&
3032 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3033 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003034 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003035 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003036 // - Otherwise (i.e., for the remaining copy-initialization cases),
3037 // user-defined conversion sequences that can convert from the source
3038 // type to the destination type or (when a conversion function is
3039 // used) to a derived class thereof are enumerated as described in
3040 // 13.3.1.4, and the best one is chosen through overload resolution
3041 // (13.3).
3042 else
3043 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3044 return;
3045 }
3046
Douglas Gregor99a2e602009-12-16 01:38:02 +00003047 if (NumArgs > 1) {
3048 SetFailed(FK_TooManyInitsForScalar);
3049 return;
3050 }
3051 assert(NumArgs == 1 && "Zero-argument case handled above");
3052
Douglas Gregor20093b42009-12-09 23:02:17 +00003053 // - Otherwise, if the source type is a (possibly cv-qualified) class
3054 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003055 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003056 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3057 return;
3058 }
3059
3060 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003061 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003062 // conversions (Clause 4) will be used, if necessary, to convert the
3063 // initializer expression to the cv-unqualified version of the
3064 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003065 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003066 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
3067}
3068
3069InitializationSequence::~InitializationSequence() {
3070 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3071 StepEnd = Steps.end();
3072 Step != StepEnd; ++Step)
3073 Step->Destroy();
3074}
3075
3076//===----------------------------------------------------------------------===//
3077// Perform initialization
3078//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003079static Sema::AssignmentAction
3080getAssignmentAction(const InitializedEntity &Entity) {
3081 switch(Entity.getKind()) {
3082 case InitializedEntity::EK_Variable:
3083 case InitializedEntity::EK_New:
3084 return Sema::AA_Initializing;
3085
3086 case InitializedEntity::EK_Parameter:
3087 // FIXME: Can we tell when we're sending vs. passing?
3088 return Sema::AA_Passing;
3089
3090 case InitializedEntity::EK_Result:
3091 return Sema::AA_Returning;
3092
3093 case InitializedEntity::EK_Exception:
3094 case InitializedEntity::EK_Base:
3095 llvm_unreachable("No assignment action for C++-specific initialization");
3096 break;
3097
3098 case InitializedEntity::EK_Temporary:
3099 // FIXME: Can we tell apart casting vs. converting?
3100 return Sema::AA_Casting;
3101
3102 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003103 case InitializedEntity::EK_ArrayElement:
3104 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003105 return Sema::AA_Initializing;
3106 }
3107
3108 return Sema::AA_Converting;
3109}
3110
Douglas Gregor2f599792010-04-02 18:24:57 +00003111static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003112 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003113 case InitializedEntity::EK_ArrayElement:
3114 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003115 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003116 case InitializedEntity::EK_New:
3117 case InitializedEntity::EK_Variable:
3118 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003119 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003120 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003121 return false;
3122
3123 case InitializedEntity::EK_Parameter:
3124 case InitializedEntity::EK_Temporary:
3125 return true;
3126 }
3127
3128 llvm_unreachable("missed an InitializedEntity kind?");
3129}
3130
Douglas Gregor523d46a2010-04-18 07:40:54 +00003131/// \brief Make a (potentially elidable) temporary copy of the object
3132/// provided by the given initializer by calling the appropriate copy
3133/// constructor.
3134///
3135/// \param S The Sema object used for type-checking.
3136///
3137/// \param T The type of the temporary object, which must either by
3138/// the type of the initializer expression or a superclass thereof.
3139///
3140/// \param Enter The entity being initialized.
3141///
3142/// \param CurInit The initializer expression.
3143///
3144/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3145/// is permitted in C++03 (but not C++0x) when binding a reference to
3146/// an rvalue.
3147///
3148/// \returns An expression that copies the initializer expression into
3149/// a temporary object, or an error expression if a copy could not be
3150/// created.
Douglas Gregor2f599792010-04-02 18:24:57 +00003151static Sema::OwningExprResult CopyObject(Sema &S,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003152 QualType T,
Douglas Gregor2f599792010-04-02 18:24:57 +00003153 const InitializedEntity &Entity,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003154 Sema::OwningExprResult CurInit,
3155 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003156 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003157 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003158 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003159 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003160 Class = cast<CXXRecordDecl>(Record->getDecl());
3161 if (!Class)
3162 return move(CurInit);
3163
3164 // C++0x [class.copy]p34:
3165 // When certain criteria are met, an implementation is allowed to
3166 // omit the copy/move construction of a class object, even if the
3167 // copy/move constructor and/or destructor for the object have
3168 // side effects. [...]
3169 // - when a temporary class object that has not been bound to a
3170 // reference (12.2) would be copied/moved to a class object
3171 // with the same cv-unqualified type, the copy/move operation
3172 // can be omitted by constructing the temporary object
3173 // directly into the target of the omitted copy/move
3174 //
3175 // Note that the other three bullets are handled elsewhere. Copy
3176 // elision for return statements and throw expressions are (FIXME:
3177 // not yet) handled as part of constructor initialization, while
3178 // copy elision for exception handlers is handled by the run-time.
3179 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregor523d46a2010-04-18 07:40:54 +00003180 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003181 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003182 switch (Entity.getKind()) {
3183 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003184 Loc = Entity.getReturnLoc();
3185 break;
3186
3187 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003188 Loc = Entity.getThrowLoc();
3189 break;
3190
3191 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003192 Loc = Entity.getDecl()->getLocation();
3193 break;
3194
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003195 case InitializedEntity::EK_ArrayElement:
3196 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003197 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003198 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003199 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003200 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003201 case InitializedEntity::EK_VectorElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003202 Loc = CurInitExpr->getLocStart();
3203 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003204 }
Douglas Gregor2f599792010-04-02 18:24:57 +00003205
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003206 // Perform overload resolution using the class's copy constructors.
3207 DeclarationName ConstructorName
3208 = S.Context.DeclarationNames.getCXXConstructorName(
3209 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3210 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003211 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003212 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3213 Con != ConEnd; ++Con) {
Douglas Gregor2f599792010-04-02 18:24:57 +00003214 // Only consider copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003215 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3216 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor153b3ba2010-04-18 02:16:12 +00003217 !Constructor->isCopyConstructor() ||
3218 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003219 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003220
3221 DeclAccessPair FoundDecl
3222 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3223 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003224 &CurInitExpr, 1, CandidateSet);
Douglas Gregor2f599792010-04-02 18:24:57 +00003225 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003226
3227 OverloadCandidateSet::iterator Best;
3228 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3229 case OR_Success:
3230 break;
3231
3232 case OR_No_Viable_Function:
3233 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003234 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003235 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003236 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3237 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003238 return S.ExprError();
3239
3240 case OR_Ambiguous:
3241 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003242 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003243 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003244 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3245 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003246 return S.ExprError();
3247
3248 case OR_Deleted:
3249 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003250 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003251 << CurInitExpr->getSourceRange();
3252 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3253 << Best->Function->isDeleted();
3254 return S.ExprError();
3255 }
3256
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003257 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3258 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3259 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003260
3261 S.CheckConstructorAccess(Loc, Constructor,
3262 Best->FoundDecl.getAccess());
3263
3264 if (IsExtraneousCopy) {
3265 // If this is a totally extraneous copy for C++03 reference
3266 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003267 // expression. We don't generate an (elided) copy operation here
3268 // because doing so would require us to pass down a flag to avoid
3269 // infinite recursion, where each step adds another extraneous,
3270 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003271
Douglas Gregor2559a702010-04-18 07:57:34 +00003272 // Instantiate the default arguments of any extra parameters in
3273 // the selected copy constructor, as if we were going to create a
3274 // proper call to the copy constructor.
3275 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3276 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3277 if (S.RequireCompleteType(Loc, Parm->getType(),
3278 S.PDiag(diag::err_call_incomplete_argument)))
3279 break;
3280
3281 // Build the default argument expression; we don't actually care
3282 // if this succeeds or not, because this routine will complain
3283 // if there was a problem.
3284 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3285 }
3286
Douglas Gregor523d46a2010-04-18 07:40:54 +00003287 return S.Owned(CurInitExpr);
3288 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003289
3290 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003291 // constructor call (we might have derived-to-base conversions, or
3292 // the copy constructor may have default arguments).
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003293 if (S.CompleteConstructorCall(Constructor,
3294 Sema::MultiExprArg(S,
3295 (void **)&CurInitExpr,
3296 1),
3297 Loc, ConstructorArgs))
3298 return S.ExprError();
3299
Douglas Gregor523d46a2010-04-18 07:40:54 +00003300 return S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003301 move_arg(ConstructorArgs));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003302}
Douglas Gregor20093b42009-12-09 23:02:17 +00003303
3304Action::OwningExprResult
3305InitializationSequence::Perform(Sema &S,
3306 const InitializedEntity &Entity,
3307 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003308 Action::MultiExprArg Args,
3309 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003310 if (SequenceKind == FailedSequence) {
3311 unsigned NumArgs = Args.size();
3312 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3313 return S.ExprError();
3314 }
3315
3316 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003317 // If the declaration is a non-dependent, incomplete array type
3318 // that has an initializer, then its type will be completed once
3319 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003320 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003321 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003322 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003323 if (const IncompleteArrayType *ArrayT
3324 = S.Context.getAsIncompleteArrayType(DeclType)) {
3325 // FIXME: We don't currently have the ability to accurately
3326 // compute the length of an initializer list without
3327 // performing full type-checking of the initializer list
3328 // (since we have to determine where braces are implicitly
3329 // introduced and such). So, we fall back to making the array
3330 // type a dependently-sized array type with no specified
3331 // bound.
3332 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3333 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003334
Douglas Gregord87b61f2009-12-10 17:56:55 +00003335 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003336 if (DeclaratorDecl *DD = Entity.getDecl()) {
3337 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3338 TypeLoc TL = TInfo->getTypeLoc();
3339 if (IncompleteArrayTypeLoc *ArrayLoc
3340 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3341 Brackets = ArrayLoc->getBracketsRange();
3342 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003343 }
3344
3345 *ResultType
3346 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3347 /*NumElts=*/0,
3348 ArrayT->getSizeModifier(),
3349 ArrayT->getIndexTypeCVRQualifiers(),
3350 Brackets);
3351 }
3352
3353 }
3354 }
3355
Eli Friedman08544622009-12-22 02:35:53 +00003356 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003357 return Sema::OwningExprResult(S, Args.release()[0]);
3358
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003359 if (Args.size() == 0)
3360 return S.Owned((Expr *)0);
3361
Douglas Gregor20093b42009-12-09 23:02:17 +00003362 unsigned NumArgs = Args.size();
3363 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3364 SourceLocation(),
3365 (Expr **)Args.release(),
3366 NumArgs,
3367 SourceLocation()));
3368 }
3369
Douglas Gregor99a2e602009-12-16 01:38:02 +00003370 if (SequenceKind == NoInitialization)
3371 return S.Owned((Expr *)0);
3372
Douglas Gregord6542d82009-12-22 15:35:07 +00003373 QualType DestType = Entity.getType().getNonReferenceType();
3374 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003375 // the same as Entity.getDecl()->getType() in cases involving type merging,
3376 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003377 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003378 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003379 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003380
Douglas Gregor99a2e602009-12-16 01:38:02 +00003381 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3382
3383 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3384
3385 // For initialization steps that start with a single initializer,
3386 // grab the only argument out the Args and place it into the "current"
3387 // initializer.
3388 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003389 case SK_ResolveAddressOfOverloadedFunction:
3390 case SK_CastDerivedToBaseRValue:
3391 case SK_CastDerivedToBaseLValue:
3392 case SK_BindReference:
3393 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003394 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003395 case SK_UserConversion:
3396 case SK_QualificationConversionLValue:
3397 case SK_QualificationConversionRValue:
3398 case SK_ConversionSequence:
3399 case SK_ListInitialization:
3400 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003401 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003402 assert(Args.size() == 1);
3403 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3404 if (CurInit.isInvalid())
3405 return S.ExprError();
3406 break;
3407
3408 case SK_ConstructorInitialization:
3409 case SK_ZeroInitialization:
3410 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003411 }
3412
3413 // Walk through the computed steps for the initialization sequence,
3414 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003415 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003416 for (step_iterator Step = step_begin(), StepEnd = step_end();
3417 Step != StepEnd; ++Step) {
3418 if (CurInit.isInvalid())
3419 return S.ExprError();
3420
3421 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003422 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003423
3424 switch (Step->Kind) {
3425 case SK_ResolveAddressOfOverloadedFunction:
3426 // Overload resolution determined which function invoke; update the
3427 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003428 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb13b7372010-02-01 03:16:54 +00003429 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003430 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003431 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003432 break;
3433
3434 case SK_CastDerivedToBaseRValue:
3435 case SK_CastDerivedToBaseLValue: {
3436 // We have a derived-to-base cast that produces either an rvalue or an
3437 // lvalue. Perform that cast.
3438
3439 // Casts to inaccessible base classes are allowed with C-style casts.
3440 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3441 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3442 CurInitExpr->getLocStart(),
3443 CurInitExpr->getSourceRange(),
3444 IgnoreBaseAccess))
3445 return S.ExprError();
3446
3447 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3448 CastExpr::CK_DerivedToBase,
3449 (Expr*)CurInit.release(),
3450 Step->Kind == SK_CastDerivedToBaseLValue));
3451 break;
3452 }
3453
3454 case SK_BindReference:
3455 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3456 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3457 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003458 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 << BitField->getDeclName()
3460 << CurInitExpr->getSourceRange();
3461 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3462 return S.ExprError();
3463 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003464
Anders Carlsson09380262010-01-31 17:18:49 +00003465 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003466 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003467 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3468 << Entity.getType().isVolatileQualified()
3469 << CurInitExpr->getSourceRange();
3470 return S.ExprError();
3471 }
3472
Douglas Gregor20093b42009-12-09 23:02:17 +00003473 // Reference binding does not have any corresponding ASTs.
3474
3475 // Check exception specifications
3476 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3477 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003478
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003480
Douglas Gregor20093b42009-12-09 23:02:17 +00003481 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003482 // Reference binding does not have any corresponding ASTs.
3483
Douglas Gregor20093b42009-12-09 23:02:17 +00003484 // Check exception specifications
3485 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3486 return S.ExprError();
3487
Douglas Gregor20093b42009-12-09 23:02:17 +00003488 break;
3489
Douglas Gregor523d46a2010-04-18 07:40:54 +00003490 case SK_ExtraneousCopyToTemporary:
3491 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3492 /*IsExtraneousCopy=*/true);
3493 break;
3494
Douglas Gregor20093b42009-12-09 23:02:17 +00003495 case SK_UserConversion: {
3496 // We have a user-defined conversion that invokes either a constructor
3497 // or a conversion function.
3498 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003499 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003500 FunctionDecl *Fn = Step->Function.Function;
3501 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003502 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003503 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003504 // Build a call to the selected constructor.
3505 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3506 SourceLocation Loc = CurInitExpr->getLocStart();
3507 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003508
Douglas Gregor20093b42009-12-09 23:02:17 +00003509 // Determine the arguments required to actually perform the constructor
3510 // call.
3511 if (S.CompleteConstructorCall(Constructor,
3512 Sema::MultiExprArg(S,
3513 (void **)&CurInitExpr,
3514 1),
3515 Loc, ConstructorArgs))
3516 return S.ExprError();
3517
3518 // Build the an expression that constructs a temporary.
3519 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3520 move_arg(ConstructorArgs));
3521 if (CurInit.isInvalid())
3522 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003523
John McCall9aa472c2010-03-19 07:35:19 +00003524 S.CheckConstructorAccess(Kind.getLocation(), Constructor,
3525 FoundFn.getAccess());
Douglas Gregor20093b42009-12-09 23:02:17 +00003526
3527 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003528 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3529 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3530 S.IsDerivedFrom(SourceType, Class))
3531 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003532 } else {
3533 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003534 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003535 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003536 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003537 FoundFn);
John McCallb13b7372010-02-01 03:16:54 +00003538
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 // FIXME: Should we move this initialization into a separate
3540 // derived-to-base conversion? I believe the answer is "no", because
3541 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003542 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003543 FoundFn, Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003544 return S.ExprError();
3545
3546 // Do a little dance to make sure that CurInit has the proper
3547 // pointer.
3548 CurInit.release();
3549
3550 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003551 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3552 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003553 if (CurInit.isInvalid() || !CurInit.get())
3554 return S.ExprError();
3555
3556 CastKind = CastExpr::CK_UserDefinedConversion;
3557 }
3558
Douglas Gregor2f599792010-04-02 18:24:57 +00003559 bool RequiresCopy = !IsCopy &&
3560 getKind() != InitializationSequence::ReferenceBinding;
3561 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003562 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3563
Douglas Gregor20093b42009-12-09 23:02:17 +00003564 CurInitExpr = CurInit.takeAs<Expr>();
3565 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3566 CastKind,
3567 CurInitExpr,
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003568 IsLvalue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003569
Douglas Gregor2f599792010-04-02 18:24:57 +00003570 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003571 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3572 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00003573 break;
3574 }
3575
3576 case SK_QualificationConversionLValue:
3577 case SK_QualificationConversionRValue:
3578 // Perform a qualification conversion; these can never go wrong.
3579 S.ImpCastExprToType(CurInitExpr, Step->Type,
3580 CastExpr::CK_NoOp,
3581 Step->Kind == SK_QualificationConversionLValue);
3582 CurInit.release();
3583 CurInit = S.Owned(CurInitExpr);
3584 break;
3585
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003586 case SK_ConversionSequence: {
3587 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3588
3589 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3590 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003591 return S.ExprError();
3592
3593 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003594 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003596 }
3597
Douglas Gregord87b61f2009-12-10 17:56:55 +00003598 case SK_ListInitialization: {
3599 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3600 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003601 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003602 return S.ExprError();
3603
3604 CurInit.release();
3605 CurInit = S.Owned(InitList);
3606 break;
3607 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003608
3609 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003610 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003611 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003612 = cast<CXXConstructorDecl>(Step->Function.Function);
John McCallb13b7372010-02-01 03:16:54 +00003613
Douglas Gregor51c56d62009-12-14 20:49:26 +00003614 // Build a call to the selected constructor.
3615 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3616 SourceLocation Loc = Kind.getLocation();
3617
3618 // Determine the arguments required to actually perform the constructor
3619 // call.
3620 if (S.CompleteConstructorCall(Constructor, move(Args),
3621 Loc, ConstructorArgs))
3622 return S.ExprError();
3623
Douglas Gregord6e44a32010-04-16 22:09:46 +00003624 // Build the expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003625 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003626 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003627 (Kind.getKind() == InitializationKind::IK_Direct ||
3628 Kind.getKind() == InitializationKind::IK_Value)) {
3629 // An explicitly-constructed temporary, e.g., X(1, 2).
3630 unsigned NumExprs = ConstructorArgs.size();
3631 Expr **Exprs = (Expr **)ConstructorArgs.take();
3632 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3633 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3634 Constructor,
3635 Entity.getType(),
3636 Kind.getLocation(),
3637 Exprs,
3638 NumExprs,
3639 Kind.getParenRange().getEnd()));
3640 } else
3641 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3642 Constructor,
3643 move_arg(ConstructorArgs),
3644 ConstructorInitRequiresZeroInit,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003645 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003646 if (CurInit.isInvalid())
3647 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003648
3649 // Only check access if all of that succeeded.
John McCall9aa472c2010-03-19 07:35:19 +00003650 S.CheckConstructorAccess(Loc, Constructor,
3651 Step->Function.FoundDecl.getAccess());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003652
Douglas Gregor2f599792010-04-02 18:24:57 +00003653 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003654 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00003655
Douglas Gregor51c56d62009-12-14 20:49:26 +00003656 break;
3657 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003658
3659 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003660 step_iterator NextStep = Step;
3661 ++NextStep;
3662 if (NextStep != StepEnd &&
3663 NextStep->Kind == SK_ConstructorInitialization) {
3664 // The need for zero-initialization is recorded directly into
3665 // the call to the object's constructor within the next step.
3666 ConstructorInitRequiresZeroInit = true;
3667 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3668 S.getLangOptions().CPlusPlus &&
3669 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003670 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3671 Kind.getRange().getBegin(),
3672 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003673 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003674 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003675 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003676 break;
3677 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003678
3679 case SK_CAssignment: {
3680 QualType SourceType = CurInitExpr->getType();
3681 Sema::AssignConvertType ConvTy =
3682 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003683
3684 // If this is a call, allow conversion to a transparent union.
3685 if (ConvTy != Sema::Compatible &&
3686 Entity.getKind() == InitializedEntity::EK_Parameter &&
3687 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3688 == Sema::Compatible)
3689 ConvTy = Sema::Compatible;
3690
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003691 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3692 Step->Type, SourceType,
3693 CurInitExpr, getAssignmentAction(Entity)))
3694 return S.ExprError();
3695
3696 CurInit.release();
3697 CurInit = S.Owned(CurInitExpr);
3698 break;
3699 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003700
3701 case SK_StringInit: {
3702 QualType Ty = Step->Type;
3703 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3704 break;
3705 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 }
3707 }
3708
3709 return move(CurInit);
3710}
3711
3712//===----------------------------------------------------------------------===//
3713// Diagnose initialization failures
3714//===----------------------------------------------------------------------===//
3715bool InitializationSequence::Diagnose(Sema &S,
3716 const InitializedEntity &Entity,
3717 const InitializationKind &Kind,
3718 Expr **Args, unsigned NumArgs) {
3719 if (SequenceKind != FailedSequence)
3720 return false;
3721
Douglas Gregord6542d82009-12-22 15:35:07 +00003722 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003723 switch (Failure) {
3724 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003725 // FIXME: Customize for the initialized entity?
3726 if (NumArgs == 0)
3727 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3728 << DestType.getNonReferenceType();
3729 else // FIXME: diagnostic below could be better!
3730 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3731 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003732 break;
3733
3734 case FK_ArrayNeedsInitList:
3735 case FK_ArrayNeedsInitListOrStringLiteral:
3736 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3737 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3738 break;
3739
John McCall6bb80172010-03-30 21:47:33 +00003740 case FK_AddressOfOverloadFailed: {
3741 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003742 S.ResolveAddressOfOverloadedFunction(Args[0],
3743 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003744 true,
3745 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003746 break;
John McCall6bb80172010-03-30 21:47:33 +00003747 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003748
3749 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003750 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003751 switch (FailedOverloadResult) {
3752 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003753 if (Failure == FK_UserConversionOverloadFailed)
3754 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3755 << Args[0]->getType() << DestType
3756 << Args[0]->getSourceRange();
3757 else
3758 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3759 << DestType << Args[0]->getType()
3760 << Args[0]->getSourceRange();
3761
John McCallcbce6062010-01-12 07:18:19 +00003762 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3763 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003764 break;
3765
3766 case OR_No_Viable_Function:
3767 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3768 << Args[0]->getType() << DestType.getNonReferenceType()
3769 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003770 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3771 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003772 break;
3773
3774 case OR_Deleted: {
3775 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3776 << Args[0]->getType() << DestType.getNonReferenceType()
3777 << Args[0]->getSourceRange();
3778 OverloadCandidateSet::iterator Best;
3779 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3780 Kind.getLocation(),
3781 Best);
3782 if (Ovl == OR_Deleted) {
3783 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3784 << Best->Function->isDeleted();
3785 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003786 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003787 }
3788 break;
3789 }
3790
3791 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003792 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003793 break;
3794 }
3795 break;
3796
3797 case FK_NonConstLValueReferenceBindingToTemporary:
3798 case FK_NonConstLValueReferenceBindingToUnrelated:
3799 S.Diag(Kind.getLocation(),
3800 Failure == FK_NonConstLValueReferenceBindingToTemporary
3801 ? diag::err_lvalue_reference_bind_to_temporary
3802 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003803 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003804 << DestType.getNonReferenceType()
3805 << Args[0]->getType()
3806 << Args[0]->getSourceRange();
3807 break;
3808
3809 case FK_RValueReferenceBindingToLValue:
3810 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3811 << Args[0]->getSourceRange();
3812 break;
3813
3814 case FK_ReferenceInitDropsQualifiers:
3815 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3816 << DestType.getNonReferenceType()
3817 << Args[0]->getType()
3818 << Args[0]->getSourceRange();
3819 break;
3820
3821 case FK_ReferenceInitFailed:
3822 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3823 << DestType.getNonReferenceType()
3824 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3825 << Args[0]->getType()
3826 << Args[0]->getSourceRange();
3827 break;
3828
3829 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003830 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3831 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003832 << DestType
3833 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3834 << Args[0]->getType()
3835 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003836 break;
3837
3838 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003839 SourceRange R;
3840
3841 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3842 R = SourceRange(InitList->getInit(1)->getLocStart(),
3843 InitList->getLocEnd());
3844 else
3845 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003846
3847 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003848 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003849 break;
3850 }
3851
3852 case FK_ReferenceBindingToInitList:
3853 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3854 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3855 break;
3856
3857 case FK_InitListBadDestinationType:
3858 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3859 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3860 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003861
3862 case FK_ConstructorOverloadFailed: {
3863 SourceRange ArgsRange;
3864 if (NumArgs)
3865 ArgsRange = SourceRange(Args[0]->getLocStart(),
3866 Args[NumArgs - 1]->getLocEnd());
3867
3868 // FIXME: Using "DestType" for the entity we're printing is probably
3869 // bad.
3870 switch (FailedOverloadResult) {
3871 case OR_Ambiguous:
3872 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3873 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003874 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003875 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003876 break;
3877
3878 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003879 if (Kind.getKind() == InitializationKind::IK_Default &&
3880 (Entity.getKind() == InitializedEntity::EK_Base ||
3881 Entity.getKind() == InitializedEntity::EK_Member) &&
3882 isa<CXXConstructorDecl>(S.CurContext)) {
3883 // This is implicit default initialization of a member or
3884 // base within a constructor. If no viable function was
3885 // found, notify the user that she needs to explicitly
3886 // initialize this base/member.
3887 CXXConstructorDecl *Constructor
3888 = cast<CXXConstructorDecl>(S.CurContext);
3889 if (Entity.getKind() == InitializedEntity::EK_Base) {
3890 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3891 << Constructor->isImplicit()
3892 << S.Context.getTypeDeclType(Constructor->getParent())
3893 << /*base=*/0
3894 << Entity.getType();
3895
3896 RecordDecl *BaseDecl
3897 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3898 ->getDecl();
3899 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
3900 << S.Context.getTagDeclType(BaseDecl);
3901 } else {
3902 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3903 << Constructor->isImplicit()
3904 << S.Context.getTypeDeclType(Constructor->getParent())
3905 << /*member=*/1
3906 << Entity.getName();
3907 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
3908
3909 if (const RecordType *Record
3910 = Entity.getType()->getAs<RecordType>())
3911 S.Diag(Record->getDecl()->getLocation(),
3912 diag::note_previous_decl)
3913 << S.Context.getTagDeclType(Record->getDecl());
3914 }
3915 break;
3916 }
3917
Douglas Gregor51c56d62009-12-14 20:49:26 +00003918 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3919 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003920 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3921 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003922 break;
3923
3924 case OR_Deleted: {
3925 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3926 << true << DestType << ArgsRange;
3927 OverloadCandidateSet::iterator Best;
3928 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3929 Kind.getLocation(),
3930 Best);
3931 if (Ovl == OR_Deleted) {
3932 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3933 << Best->Function->isDeleted();
3934 } else {
3935 llvm_unreachable("Inconsistent overload resolution?");
3936 }
3937 break;
3938 }
3939
3940 case OR_Success:
3941 llvm_unreachable("Conversion did not fail!");
3942 break;
3943 }
3944 break;
3945 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003946
3947 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003948 if (Entity.getKind() == InitializedEntity::EK_Member &&
3949 isa<CXXConstructorDecl>(S.CurContext)) {
3950 // This is implicit default-initialization of a const member in
3951 // a constructor. Complain that it needs to be explicitly
3952 // initialized.
3953 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
3954 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
3955 << Constructor->isImplicit()
3956 << S.Context.getTypeDeclType(Constructor->getParent())
3957 << /*const=*/1
3958 << Entity.getName();
3959 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
3960 << Entity.getName();
3961 } else {
3962 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3963 << DestType << (bool)DestType->getAs<RecordType>();
3964 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003965 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003966 }
3967
3968 return true;
3969}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003970
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003971void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3972 switch (SequenceKind) {
3973 case FailedSequence: {
3974 OS << "Failed sequence: ";
3975 switch (Failure) {
3976 case FK_TooManyInitsForReference:
3977 OS << "too many initializers for reference";
3978 break;
3979
3980 case FK_ArrayNeedsInitList:
3981 OS << "array requires initializer list";
3982 break;
3983
3984 case FK_ArrayNeedsInitListOrStringLiteral:
3985 OS << "array requires initializer list or string literal";
3986 break;
3987
3988 case FK_AddressOfOverloadFailed:
3989 OS << "address of overloaded function failed";
3990 break;
3991
3992 case FK_ReferenceInitOverloadFailed:
3993 OS << "overload resolution for reference initialization failed";
3994 break;
3995
3996 case FK_NonConstLValueReferenceBindingToTemporary:
3997 OS << "non-const lvalue reference bound to temporary";
3998 break;
3999
4000 case FK_NonConstLValueReferenceBindingToUnrelated:
4001 OS << "non-const lvalue reference bound to unrelated type";
4002 break;
4003
4004 case FK_RValueReferenceBindingToLValue:
4005 OS << "rvalue reference bound to an lvalue";
4006 break;
4007
4008 case FK_ReferenceInitDropsQualifiers:
4009 OS << "reference initialization drops qualifiers";
4010 break;
4011
4012 case FK_ReferenceInitFailed:
4013 OS << "reference initialization failed";
4014 break;
4015
4016 case FK_ConversionFailed:
4017 OS << "conversion failed";
4018 break;
4019
4020 case FK_TooManyInitsForScalar:
4021 OS << "too many initializers for scalar";
4022 break;
4023
4024 case FK_ReferenceBindingToInitList:
4025 OS << "referencing binding to initializer list";
4026 break;
4027
4028 case FK_InitListBadDestinationType:
4029 OS << "initializer list for non-aggregate, non-scalar type";
4030 break;
4031
4032 case FK_UserConversionOverloadFailed:
4033 OS << "overloading failed for user-defined conversion";
4034 break;
4035
4036 case FK_ConstructorOverloadFailed:
4037 OS << "constructor overloading failed";
4038 break;
4039
4040 case FK_DefaultInitOfConst:
4041 OS << "default initialization of a const variable";
4042 break;
4043 }
4044 OS << '\n';
4045 return;
4046 }
4047
4048 case DependentSequence:
4049 OS << "Dependent sequence: ";
4050 return;
4051
4052 case UserDefinedConversion:
4053 OS << "User-defined conversion sequence: ";
4054 break;
4055
4056 case ConstructorInitialization:
4057 OS << "Constructor initialization sequence: ";
4058 break;
4059
4060 case ReferenceBinding:
4061 OS << "Reference binding: ";
4062 break;
4063
4064 case ListInitialization:
4065 OS << "List initialization: ";
4066 break;
4067
4068 case ZeroInitialization:
4069 OS << "Zero initialization\n";
4070 return;
4071
4072 case NoInitialization:
4073 OS << "No initialization\n";
4074 return;
4075
4076 case StandardConversion:
4077 OS << "Standard conversion: ";
4078 break;
4079
4080 case CAssignment:
4081 OS << "C assignment: ";
4082 break;
4083
4084 case StringInit:
4085 OS << "String initialization: ";
4086 break;
4087 }
4088
4089 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4090 if (S != step_begin()) {
4091 OS << " -> ";
4092 }
4093
4094 switch (S->Kind) {
4095 case SK_ResolveAddressOfOverloadedFunction:
4096 OS << "resolve address of overloaded function";
4097 break;
4098
4099 case SK_CastDerivedToBaseRValue:
4100 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4101 break;
4102
4103 case SK_CastDerivedToBaseLValue:
4104 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4105 break;
4106
4107 case SK_BindReference:
4108 OS << "bind reference to lvalue";
4109 break;
4110
4111 case SK_BindReferenceToTemporary:
4112 OS << "bind reference to a temporary";
4113 break;
4114
Douglas Gregor523d46a2010-04-18 07:40:54 +00004115 case SK_ExtraneousCopyToTemporary:
4116 OS << "extraneous C++03 copy to temporary";
4117 break;
4118
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004119 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004120 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004121 break;
4122
4123 case SK_QualificationConversionRValue:
4124 OS << "qualification conversion (rvalue)";
4125
4126 case SK_QualificationConversionLValue:
4127 OS << "qualification conversion (lvalue)";
4128 break;
4129
4130 case SK_ConversionSequence:
4131 OS << "implicit conversion sequence (";
4132 S->ICS->DebugPrint(); // FIXME: use OS
4133 OS << ")";
4134 break;
4135
4136 case SK_ListInitialization:
4137 OS << "list initialization";
4138 break;
4139
4140 case SK_ConstructorInitialization:
4141 OS << "constructor initialization";
4142 break;
4143
4144 case SK_ZeroInitialization:
4145 OS << "zero initialization";
4146 break;
4147
4148 case SK_CAssignment:
4149 OS << "C assignment";
4150 break;
4151
4152 case SK_StringInit:
4153 OS << "string initialization";
4154 break;
4155 }
4156 }
4157}
4158
4159void InitializationSequence::dump() const {
4160 dump(llvm::errs());
4161}
4162
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004163//===----------------------------------------------------------------------===//
4164// Initialization helper functions
4165//===----------------------------------------------------------------------===//
4166Sema::OwningExprResult
4167Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4168 SourceLocation EqualLoc,
4169 OwningExprResult Init) {
4170 if (Init.isInvalid())
4171 return ExprError();
4172
4173 Expr *InitE = (Expr *)Init.get();
4174 assert(InitE && "No initialization expression?");
4175
4176 if (EqualLoc.isInvalid())
4177 EqualLoc = InitE->getLocStart();
4178
4179 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4180 EqualLoc);
4181 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4182 Init.release();
4183 return Seq.Perform(*this, Entity, Kind,
4184 MultiExprArg(*this, (void**)&InitE, 1));
4185}