blob: 18164d685f6f565912646da71ebd82afaeb0eaaa [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"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000025#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000026using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000027
Chris Lattnerdd8e0062009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
Chris Lattner79e079d2009-02-24 23:10:27 +000032static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000033 const ArrayType *AT = Context.getAsArrayType(DeclType);
34 if (!AT) return 0;
35
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
Mike Stump1eb44332009-09-09 15:08:12 +000067static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner95e8d652009-02-24 22:46:58 +000068 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000069 // Get the type before calling CheckSingleAssignmentConstraints(), since
70 // it can promote the expression.
Mike Stump1eb44332009-09-09 15:08:12 +000071 QualType InitType = Init->getType();
72
Chris Lattner95e8d652009-02-24 22:46:58 +000073 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000075 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000076 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000077 ImplicitConversionSequence ICS;
78 OverloadCandidateSet CandidateSet;
79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80 CandidateSet,
Douglas Gregor20093b42009-12-09 23:02:17 +000081 true, false, false) != OR_Ambiguous)
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000082 return S.Diag(Init->getSourceRange().getBegin(),
83 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +000084 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000085 << Init->getSourceRange();
86 S.Diag(Init->getSourceRange().getBegin(),
87 diag::err_typecheck_convert_ambiguous)
88 << DeclType << Init->getType() << Init->getSourceRange();
89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
90 return true;
91 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 return false;
93 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattner95e8d652009-02-24 22:46:58 +000095 Sema::AssignConvertType ConvTy =
96 S.CheckSingleAssignmentConstraints(DeclType, Init);
97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000098 InitType, Init, Sema::AA_Initializing);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000099}
100
Chris Lattner79e079d2009-02-24 23:10:27 +0000101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102 // Get the length of the string as parsed.
103 uint64_t StrLength =
104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner79e079d2009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000117 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Eli Friedman8718a6a2009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Eli Friedman8718a6a2009-05-29 18:22:49 +0000122 // C99 6.7.8p14. We have an array of character type with known size. However,
123 // the size may be smaller or larger than the string we are initializing.
124 // FIXME: Avoid truncation for 64-bit length strings.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000138 const InitializedEntity &Entity,
139 const InitializationKind &Kind) {
140 SourceLocation InitLoc = Kind.getLocation();
141 DeclarationName InitEntity = Entity.getName();
142 bool DirectInit = (Kind.getKind() == InitializationKind::IK_Direct);
143
Mike Stump1eb44332009-09-09 15:08:12 +0000144 if (DeclType->isDependentType() ||
Douglas Gregorcb78d882009-11-19 18:03:26 +0000145 Init->isTypeDependent() || Init->isValueDependent()) {
146 // We have either a dependent type or a type- or value-dependent
147 // initializer, so we don't perform any additional checking at
148 // this point.
149
150 // If the declaration is a non-dependent, incomplete array type
151 // that has an initializer, then its type will be completed once
Douglas Gregor73460a32009-11-19 23:25:22 +0000152 // the initializer is instantiated.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000153 if (!DeclType->isDependentType()) {
154 if (const IncompleteArrayType *ArrayT
155 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregor73460a32009-11-19 23:25:22 +0000156 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
157 if (!ILE->isTypeDependent()) {
158 // Compute the constant array type from the length of the
159 // initializer list.
160 // FIXME: This will be wrong if there are designated
161 // initializations. Good thing they don't exist in C++!
162 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
163 ILE->getNumInits());
164 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
165 if (NumElements == Zero) {
166 // Sizing an array implicitly to zero is not allowed by ISO C,
167 // but is supported by GNU.
168 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
169 }
170
171 DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
172 NumElements,
173 ArrayT->getSizeModifier(),
174 ArrayT->getIndexTypeCVRQualifiers());
175 return false;
176 }
177 }
178
179 // Make the array type-dependent by making it dependently-sized.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000180 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
181 /*NumElts=*/0,
182 ArrayT->getSizeModifier(),
183 ArrayT->getIndexTypeCVRQualifiers(),
184 SourceRange());
185 }
186 }
187
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000188 return false;
Douglas Gregorcb78d882009-11-19 18:03:26 +0000189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000191 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000192 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000193 // (8.3.2), shall be initialized by an object, or function, of
194 // type T or by an object that can be converted into a T.
Douglas Gregor52bb5d22009-12-16 16:54:16 +0000195 if (DeclType->isReferenceType()) {
196 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
197 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
198 MultiExprArg(*this, (void**)&Init, 1),
199 &DeclType);
200 if (CurInit.isInvalid())
201 return true;
202
203 Init = CurInit.takeAs<Expr>();
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000207 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
208 // of unknown size ("[]") or an object type that is not a variable array type.
209 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
210 return Diag(InitLoc, diag::err_variable_object_no_init)
211 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000213 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
214 if (!InitList) {
215 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000216 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
217 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000218 return false;
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000221 // C++ [dcl.init]p14:
222 // -- If the destination type is a (possibly cv-qualified) class
223 // type:
224 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
Douglas Gregor7abfbdb2009-12-19 03:01:41 +0000225 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
226 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
227 MultiExprArg(*this, (void**)&Init, 1),
228 &DeclType);
229 if (CurInit.isInvalid())
230 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Douglas Gregor7abfbdb2009-12-19 03:01:41 +0000232 Init = CurInit.takeAs<Expr>();
233 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000234 }
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000236 // C99 6.7.8p16.
237 if (DeclType->isArrayType())
238 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000239 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattner95e8d652009-02-24 22:46:58 +0000241 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000242 }
243
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000244 bool hadError = CheckInitList(Entity, InitList, DeclType);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000245 Init = InitList;
246 return hadError;
247}
248
249//===----------------------------------------------------------------------===//
250// Semantic checking for initializer lists.
251//===----------------------------------------------------------------------===//
252
Douglas Gregor9e80f722009-01-29 01:05:33 +0000253/// @brief Semantic checking for initializer lists.
254///
255/// The InitListChecker class contains a set of routines that each
256/// handle the initialization of a certain kind of entity, e.g.,
257/// arrays, vectors, struct/union types, scalars, etc. The
258/// InitListChecker itself performs a recursive walk of the subobject
259/// structure of the type to be initialized, while stepping through
260/// the initializer list one element at a time. The IList and Index
261/// parameters to each of the Check* routines contain the active
262/// (syntactic) initializer list and the index into that initializer
263/// list that represents the current initializer. Each routine is
264/// responsible for moving that Index forward as it consumes elements.
265///
266/// Each Check* routine also has a StructuredList/StructuredIndex
267/// arguments, which contains the current the "structured" (semantic)
268/// initializer list and the index into that initializer list where we
269/// are copying initializers as we map them over to the semantic
270/// list. Once we have completed our recursive walk of the subobject
271/// structure, we will have constructed a full semantic initializer
272/// list.
273///
274/// C99 designators cause changes in the initializer list traversal,
275/// because they make the initialization "jump" into a specific
276/// subobject and then continue the initialization from that
277/// point. CheckDesignatedInitializer() recursively steps into the
278/// designated subobject and manages backing out the recursion to
279/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000280namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000281class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000282 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000283 bool hadError;
284 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
285 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000286
287 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000288 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000291 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000292 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000293 unsigned &StructuredIndex,
294 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000295 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
296 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000297 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000299 unsigned &StructuredIndex,
300 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000301 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000302 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000303 InitListExpr *StructuredList,
304 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000305 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000306 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000309 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000310 unsigned &Index,
311 InitListExpr *StructuredList,
312 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000313 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000314 InitListExpr *StructuredList,
315 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000316 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
317 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000318 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000319 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000320 unsigned &StructuredIndex,
321 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000322 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
323 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000324 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000325 InitListExpr *StructuredList,
326 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000327 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000328 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000329 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000330 RecordDecl::field_iterator *NextField,
331 llvm::APSInt *NextElementIndex,
332 unsigned &Index,
333 InitListExpr *StructuredList,
334 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000335 bool FinishSubobjectInit,
336 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000337 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
338 QualType CurrentObjectType,
339 InitListExpr *StructuredList,
340 unsigned StructuredIndex,
341 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000342 void UpdateStructuredListElement(InitListExpr *StructuredList,
343 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000344 Expr *expr);
345 int numArrayElements(QualType DeclType);
346 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000347
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000348 void FillInValueInitializations(const InitializedEntity &Entity,
349 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000350public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351 InitListChecker(Sema &S, const InitializedEntity &Entity,
352 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000353 bool HadError() { return hadError; }
354
355 // @brief Retrieves the fully-structured initializer list used for
356 // semantic analysis and code generation.
357 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
358};
Chris Lattner8b419b92009-02-24 22:48:58 +0000359} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000360
Douglas Gregor4c678342009-01-28 21:54:33 +0000361/// Recursively replaces NULL values within the given initializer list
362/// with expressions that perform value-initialization of the
363/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000364void
365InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
366 InitListExpr *ILE,
367 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000368 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000369 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000370 SourceLocation Loc = ILE->getSourceRange().getBegin();
371 if (ILE->getSyntacticForm())
372 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek6217b802009-07-29 21:53:49 +0000374 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000375 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000376 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000377 Field = RType->getDecl()->field_begin(),
378 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000379 Field != FieldEnd; ++Field) {
380 if (Field->isUnnamedBitfield())
381 continue;
382
Douglas Gregor16006c92009-12-16 18:50:27 +0000383 if (hadError)
384 return;
385
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000386 InitializedEntity MemberEntity
387 = InitializedEntity::InitializeMember(*Field, &Entity);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000389 // FIXME: We probably don't need to handle references
390 // specially here, since value-initialization of references is
391 // handled in InitializationSequence.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000392 if (Field->getType()->isReferenceType()) {
393 // C++ [dcl.init.aggr]p9:
394 // If an incomplete or empty initializer-list leaves a
395 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000396 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000397 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000398 << Field->getType()
399 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000400 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000401 diag::note_uninit_reference_member);
402 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 return;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404 }
405
406 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
407 true);
408 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
409 if (!InitSeq) {
410 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000411 hadError = true;
412 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000413 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000414
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 Sema::OwningExprResult MemberInit
416 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
417 Sema::MultiExprArg(SemaRef, 0, 0));
418 if (MemberInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000419 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000420 return;
421 }
422
423 if (hadError) {
424 // Do nothing
425 } else if (Init < NumInits) {
426 ILE->setInit(Init, MemberInit.takeAs<Expr>());
427 } else if (InitSeq.getKind()
428 == InitializationSequence::ConstructorInitialization) {
429 // Value-initialization requires a constructor call, so
430 // extend the initializer list to include the constructor
431 // call and make a note that we'll need to take another pass
432 // through the initializer list.
433 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
434 RequiresSecondPass = true;
435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000437 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000438 FillInValueInitializations(MemberEntity, InnerILE,
439 RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000440 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000441
442 // Only look at the first initialization of a union.
443 if (RType->getDecl()->isUnion())
444 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000445 }
446
447 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000448 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000449
450 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000452 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000453 unsigned NumInits = ILE->getNumInits();
454 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000455 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000456 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000457 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
458 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000459 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
460 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000461 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000462 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000463 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000464 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
465 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000466 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000467 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000469
Douglas Gregor87fd7032009-02-02 17:43:21 +0000470 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000471 if (hadError)
472 return;
473
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000474 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
475 ElementEntity.setElementIndex(Init);
476
Douglas Gregor87fd7032009-02-02 17:43:21 +0000477 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000478 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
479 true);
480 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
481 if (!InitSeq) {
482 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000483 hadError = true;
484 return;
485 }
486
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000487 Sema::OwningExprResult ElementInit
488 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
489 Sema::MultiExprArg(SemaRef, 0, 0));
490 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000491 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000492 return;
493 }
494
495 if (hadError) {
496 // Do nothing
497 } else if (Init < NumInits) {
498 ILE->setInit(Init, ElementInit.takeAs<Expr>());
499 } else if (InitSeq.getKind()
500 == InitializationSequence::ConstructorInitialization) {
501 // Value-initialization requires a constructor call, so
502 // extend the initializer list to include the constructor
503 // call and make a note that we'll need to take another pass
504 // through the initializer list.
505 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
506 RequiresSecondPass = true;
507 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000508 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000509 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
510 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000511 }
512}
513
Chris Lattner68355a52009-01-29 05:10:57 +0000514
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000515InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
516 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000517 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000518 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000519
Eli Friedmanb85f7072008-05-19 19:16:24 +0000520 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000522 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000523 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000524 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
525 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000526
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000527 if (!hadError) {
528 bool RequiresSecondPass = false;
529 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000530 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000531 FillInValueInitializations(Entity, FullyStructuredList,
532 RequiresSecondPass);
533 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000534}
535
536int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000537 // FIXME: use a proper constant
538 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000539 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000540 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000541 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
542 }
543 return maxElements;
544}
545
546int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000548 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000549 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000550 Field = structDecl->field_begin(),
551 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 Field != FieldEnd; ++Field) {
553 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
554 ++InitializableMembers;
555 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000556 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000557 return std::min(InitializableMembers, 1);
558 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000559}
560
Mike Stump1eb44332009-09-09 15:08:12 +0000561void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000562 QualType T, unsigned &Index,
563 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000564 unsigned &StructuredIndex,
565 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000566 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Steve Naroff0cca7492008-05-01 22:18:59 +0000568 if (T->isArrayType())
569 maxElements = numArrayElements(T);
570 else if (T->isStructureType() || T->isUnionType())
571 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000572 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000573 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000574 else
575 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000576
Eli Friedman402256f2008-05-25 13:49:22 +0000577 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000578 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000579 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000580 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000581 hadError = true;
582 return;
583 }
584
Douglas Gregor4c678342009-01-28 21:54:33 +0000585 // Build a structured initializer list corresponding to this subobject.
586 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000587 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
588 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000589 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
590 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000591 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000592
Douglas Gregor4c678342009-01-28 21:54:33 +0000593 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000594 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000596 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000597 StructuredSubobjectInitIndex,
598 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000599 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000600 StructuredSubobjectInitList->setType(T);
601
Douglas Gregored8a93d2009-03-01 17:12:46 +0000602 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000603 // range corresponds with the end of the last initializer it used.
604 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000605 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000606 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
607 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
608 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000609}
610
Steve Naroffa647caa2008-05-06 00:23:44 +0000611void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 unsigned &Index,
613 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000614 unsigned &StructuredIndex,
615 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000616 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000617 SyntacticToSemantic[IList] = StructuredList;
618 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000619 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000620 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000621 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000622 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000623 if (hadError)
624 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000625
Eli Friedman638e1442008-05-25 13:22:35 +0000626 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000627 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000628 if (StructuredIndex == 1 &&
629 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000630 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000631 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000632 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000633 hadError = true;
634 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000635 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000636 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000637 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000638 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000639 // Don't complain for incomplete types, since we'll get an error
640 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000641 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000642 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000643 CurrentObjectType->isArrayType()? 0 :
644 CurrentObjectType->isVectorType()? 1 :
645 CurrentObjectType->isScalarType()? 2 :
646 CurrentObjectType->isUnionType()? 3 :
647 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000648
649 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000650 if (SemaRef.getLangOptions().CPlusPlus) {
651 DK = diag::err_excess_initializers;
652 hadError = true;
653 }
Nate Begeman08634522009-07-07 21:53:06 +0000654 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
655 DK = diag::err_excess_initializers;
656 hadError = true;
657 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000658
Chris Lattner08202542009-02-24 22:50:46 +0000659 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000660 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000661 }
662 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000663
Eli Friedman759f2522009-05-16 11:45:48 +0000664 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000666 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000667 << CodeModificationHint::CreateRemoval(IList->getLocStart())
668 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000669}
670
Eli Friedmanb85f7072008-05-19 19:16:24 +0000671void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000672 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000673 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000676 unsigned &StructuredIndex,
677 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000678 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000679 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000680 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000681 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000682 } else if (DeclType->isAggregateType()) {
683 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000685 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000686 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000687 StructuredList, StructuredIndex,
688 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000689 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000690 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000691 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000692 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000693 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
694 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000695 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000696 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000697 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
698 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000699 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000700 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000701 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000702 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000703 } else if (DeclType->isRecordType()) {
704 // C++ [dcl.init]p14:
705 // [...] If the class is an aggregate (8.5.1), and the initializer
706 // is a brace-enclosed list, see 8.5.1.
707 //
708 // Note: 8.5.1 is handled below; here, we diagnose the case where
709 // we have an initializer list and a destination type that is not
710 // an aggregate.
711 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000712 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000713 << DeclType << IList->getSourceRange();
714 hadError = true;
715 } else if (DeclType->isReferenceType()) {
716 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000717 } else {
718 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000719 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000720 assert(0 && "Unsupported initializer type");
721 }
722}
723
Eli Friedmanb85f7072008-05-19 19:16:24 +0000724void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000725 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000726 unsigned &Index,
727 InitListExpr *StructuredList,
728 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000729 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000730 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
731 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000732 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000733 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000734 = getStructuredSubobjectInit(IList, Index, ElemType,
735 StructuredList, StructuredIndex,
736 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000737 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000738 newStructuredList, newStructuredIndex);
739 ++StructuredIndex;
740 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000741 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
742 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000743 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000744 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000745 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000746 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000747 } else if (ElemType->isReferenceType()) {
748 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000749 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000750 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000751 // C++ [dcl.init.aggr]p12:
752 // All implicit type conversions (clause 4) are considered when
753 // initializing the aggregate member with an ini- tializer from
754 // an initializer-list. If the initializer can initialize a
755 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000756 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000757 = SemaRef.TryCopyInitialization(expr, ElemType,
758 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000759 /*ForceRValue=*/false,
760 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000761
Douglas Gregor930d8b52009-01-30 22:09:00 +0000762 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000763 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000764 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000765 hadError = true;
766 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
767 ++Index;
768 return;
769 }
770
771 // Fall through for subaggregate initialization
772 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000773 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000774 //
775 // The initializer for a structure or union object that has
776 // automatic storage duration shall be either an initializer
777 // list as described below, or a single expression that has
778 // compatible structure or union type. In the latter case, the
779 // initial value of the object, including unnamed members, is
780 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000781 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000782 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000783 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
784 ++Index;
785 return;
786 }
787
788 // Fall through for subaggregate initialization
789 }
790
791 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000792 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000793 // [...] Otherwise, if the member is itself a non-empty
794 // subaggregate, brace elision is assumed and the initializer is
795 // considered for the initialization of the first member of
796 // the subaggregate.
797 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000798 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000799 StructuredIndex);
800 ++StructuredIndex;
801 } else {
802 // We cannot initialize this element, so let
803 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000804 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000805 hadError = true;
806 ++Index;
807 ++StructuredIndex;
808 }
809 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000810}
811
Douglas Gregor930d8b52009-01-30 22:09:00 +0000812void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000813 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000814 InitListExpr *StructuredList,
815 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000816 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000817 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000818 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000819 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000820 diag::err_many_braces_around_scalar_init)
821 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000822 hadError = true;
823 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000824 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000825 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000826 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000827 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000828 diag::err_designator_for_scalar_init)
829 << DeclType << expr->getSourceRange();
830 hadError = true;
831 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000832 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000833 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000834 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000835
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000836 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000837 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000838 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000839 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000840 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000841 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000842 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000843 if (hadError)
844 ++StructuredIndex;
845 else
846 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000847 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000848 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000849 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000850 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000851 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000852 ++Index;
853 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000854 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000855 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000856}
857
Douglas Gregor930d8b52009-01-30 22:09:00 +0000858void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
859 unsigned &Index,
860 InitListExpr *StructuredList,
861 unsigned &StructuredIndex) {
862 if (Index < IList->getNumInits()) {
863 Expr *expr = IList->getInit(Index);
864 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000866 << DeclType << IList->getSourceRange();
867 hadError = true;
868 ++Index;
869 ++StructuredIndex;
870 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000871 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000872
873 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000874 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000875 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000876 /*SuppressUserConversions=*/false,
877 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000878 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000879 hadError = true;
880 else if (savExpr != expr) {
881 // The type was promoted, update initializer list.
882 IList->setInit(Index, expr);
883 }
884 if (hadError)
885 ++StructuredIndex;
886 else
887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
888 ++Index;
889 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000890 // FIXME: It would be wonderful if we could point at the actual member. In
891 // general, it would be useful to pass location information down the stack,
892 // so that we know the location (or decl) of the "current object" being
893 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000894 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000895 diag::err_init_reference_member_uninitialized)
896 << DeclType
897 << IList->getSourceRange();
898 hadError = true;
899 ++Index;
900 ++StructuredIndex;
901 return;
902 }
903}
904
Mike Stump1eb44332009-09-09 15:08:12 +0000905void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000906 unsigned &Index,
907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000909 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000910 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000911 unsigned maxElements = VT->getNumElements();
912 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000913 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Nate Begeman2ef13e52009-08-10 23:49:36 +0000915 if (!SemaRef.getLangOptions().OpenCL) {
916 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
917 // Don't attempt to go past the end of the init list
918 if (Index >= IList->getNumInits())
919 break;
920 CheckSubElementType(IList, elementType, Index,
921 StructuredList, StructuredIndex);
922 }
923 } else {
924 // OpenCL initializers allows vectors to be constructed from vectors.
925 for (unsigned i = 0; i < maxElements; ++i) {
926 // Don't attempt to go past the end of the init list
927 if (Index >= IList->getNumInits())
928 break;
929 QualType IType = IList->getInit(Index)->getType();
930 if (!IType->isVectorType()) {
931 CheckSubElementType(IList, elementType, Index,
932 StructuredList, StructuredIndex);
933 ++numEltsInit;
934 } else {
John McCall183700f2009-09-21 23:43:11 +0000935 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000936 unsigned numIElts = IVT->getNumElements();
937 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
938 numIElts);
939 CheckSubElementType(IList, VecType, Index,
940 StructuredList, StructuredIndex);
941 numEltsInit += numIElts;
942 }
943 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Nate Begeman2ef13e52009-08-10 23:49:36 +0000946 // OpenCL & AltiVec require all elements to be initialized.
947 if (numEltsInit != maxElements)
948 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
949 SemaRef.Diag(IList->getSourceRange().getBegin(),
950 diag::err_vector_incorrect_num_initializers)
951 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000952 }
953}
954
Mike Stump1eb44332009-09-09 15:08:12 +0000955void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000956 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000957 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000958 unsigned &Index,
959 InitListExpr *StructuredList,
960 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000961 // Check for the special-case of initializing an array with a string.
962 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000963 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
964 SemaRef.Context)) {
965 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000966 // We place the string literal directly into the resulting
967 // initializer list. This is the only place where the structure
968 // of the structured initializer list doesn't match exactly,
969 // because doing so would involve allocating one character
970 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000971 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000972 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000973 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000974 return;
975 }
976 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000977 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000978 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000979 // Check for VLAs; in standard C it would be possible to check this
980 // earlier, but I don't know where clang accepts VLAs (gcc accepts
981 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000982 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000983 diag::err_variable_object_no_init)
984 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000985 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000986 ++Index;
987 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000988 return;
989 }
990
Douglas Gregor05c13a32009-01-22 00:58:24 +0000991 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000992 llvm::APSInt maxElements(elementIndex.getBitWidth(),
993 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994 bool maxElementsKnown = false;
995 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000996 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000997 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000998 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000999 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001000 maxElementsKnown = true;
1001 }
1002
Chris Lattner08202542009-02-24 22:50:46 +00001003 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001004 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001005 while (Index < IList->getNumInits()) {
1006 Expr *Init = IList->getInit(Index);
1007 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001008 // If we're not the subobject that matches up with the '{' for
1009 // the designator, we shouldn't be handling the
1010 // designator. Return immediately.
1011 if (!SubobjectIsDesignatorContext)
1012 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001013
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001014 // Handle this designated initializer. elementIndex will be
1015 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +00001016 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001017 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001018 StructuredList, StructuredIndex, true,
1019 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001020 hadError = true;
1021 continue;
1022 }
1023
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001024 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1025 maxElements.extend(elementIndex.getBitWidth());
1026 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1027 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001028 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001029
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001030 // If the array is of incomplete type, keep track of the number of
1031 // elements in the initializer.
1032 if (!maxElementsKnown && elementIndex > maxElements)
1033 maxElements = elementIndex;
1034
Douglas Gregor05c13a32009-01-22 00:58:24 +00001035 continue;
1036 }
1037
1038 // If we know the maximum number of elements, and we've already
1039 // hit it, stop consuming elements in the initializer list.
1040 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001041 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001042
1043 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001044 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001045 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001046 ++elementIndex;
1047
1048 // If the array is of incomplete type, keep track of the number of
1049 // elements in the initializer.
1050 if (!maxElementsKnown && elementIndex > maxElements)
1051 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001052 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001053 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001054 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001055 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001056 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001057 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001058 // Sizing an array implicitly to zero is not allowed by ISO C,
1059 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001060 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001061 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001062 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001063
Mike Stump1eb44332009-09-09 15:08:12 +00001064 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001065 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001066 }
1067}
1068
Mike Stump1eb44332009-09-09 15:08:12 +00001069void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1070 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001071 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001072 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001073 unsigned &Index,
1074 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001075 unsigned &StructuredIndex,
1076 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001077 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Eli Friedmanb85f7072008-05-19 19:16:24 +00001079 // If the record is invalid, some of it's members are invalid. To avoid
1080 // confusion, we forgo checking the intializer for the entire record.
1081 if (structDecl->isInvalidDecl()) {
1082 hadError = true;
1083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001084 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001085
1086 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1087 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001088 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001089 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001090 Field != FieldEnd; ++Field) {
1091 if (Field->getDeclName()) {
1092 StructuredList->setInitializedFieldInUnion(*Field);
1093 break;
1094 }
1095 }
1096 return;
1097 }
1098
Douglas Gregor05c13a32009-01-22 00:58:24 +00001099 // If structDecl is a forward declaration, this loop won't do
1100 // anything except look at designated initializers; That's okay,
1101 // because an error should get printed out elsewhere. It might be
1102 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001103 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001104 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001105 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001106 while (Index < IList->getNumInits()) {
1107 Expr *Init = IList->getInit(Index);
1108
1109 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001110 // If we're not the subobject that matches up with the '{' for
1111 // the designator, we shouldn't be handling the
1112 // designator. Return immediately.
1113 if (!SubobjectIsDesignatorContext)
1114 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001115
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001116 // Handle this designated initializer. Field will be updated to
1117 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001118 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001119 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001120 StructuredList, StructuredIndex,
1121 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001122 hadError = true;
1123
Douglas Gregordfb5e592009-02-12 19:00:39 +00001124 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001125 continue;
1126 }
1127
1128 if (Field == FieldEnd) {
1129 // We've run out of fields. We're done.
1130 break;
1131 }
1132
Douglas Gregordfb5e592009-02-12 19:00:39 +00001133 // We've already initialized a member of a union. We're done.
1134 if (InitializedSomething && DeclType->isUnionType())
1135 break;
1136
Douglas Gregor44b43212008-12-11 16:49:14 +00001137 // If we've hit the flexible array member at the end, we're done.
1138 if (Field->getType()->isIncompleteArrayType())
1139 break;
1140
Douglas Gregor0bb76892009-01-29 16:53:55 +00001141 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001142 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001143 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001144 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001145 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001146
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001147 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001148 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001149 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001150
1151 if (DeclType->isUnionType()) {
1152 // Initialize the first field within the union.
1153 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001154 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001155
1156 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001157 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001158
Mike Stump1eb44332009-09-09 15:08:12 +00001159 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001160 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001161 return;
1162
1163 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001164 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001165 (!isa<InitListExpr>(IList->getInit(Index)) ||
1166 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001167 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001168 diag::err_flexible_array_init_nonempty)
1169 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001170 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001171 << *Field;
1172 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001173 ++Index;
1174 return;
1175 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001176 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001177 diag::ext_flexible_array_init)
1178 << IList->getInit(Index)->getSourceRange().getBegin();
1179 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1180 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001181 }
1182
Douglas Gregora6457962009-03-20 00:32:56 +00001183 if (isa<InitListExpr>(IList->getInit(Index)))
1184 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1185 StructuredIndex);
1186 else
1187 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1188 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001189}
Steve Naroff0cca7492008-05-01 22:18:59 +00001190
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001191/// \brief Expand a field designator that refers to a member of an
1192/// anonymous struct or union into a series of field designators that
1193/// refers to the field within the appropriate subobject.
1194///
1195/// Field/FieldIndex will be updated to point to the (new)
1196/// currently-designated field.
1197static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001198 DesignatedInitExpr *DIE,
1199 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001200 FieldDecl *Field,
1201 RecordDecl::field_iterator &FieldIter,
1202 unsigned &FieldIndex) {
1203 typedef DesignatedInitExpr::Designator Designator;
1204
1205 // Build the path from the current object to the member of the
1206 // anonymous struct/union (backwards).
1207 llvm::SmallVector<FieldDecl *, 4> Path;
1208 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001210 // Build the replacement designators.
1211 llvm::SmallVector<Designator, 4> Replacements;
1212 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1213 FI = Path.rbegin(), FIEnd = Path.rend();
1214 FI != FIEnd; ++FI) {
1215 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001216 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001217 DIE->getDesignator(DesigIdx)->getDotLoc(),
1218 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1219 else
1220 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1221 SourceLocation()));
1222 Replacements.back().setField(*FI);
1223 }
1224
1225 // Expand the current designator into the set of replacement
1226 // designators, so we have a full subobject path down to where the
1227 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001229 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001231 // Update FieldIter/FieldIndex;
1232 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001233 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001234 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001235 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001236 FieldIter != FEnd; ++FieldIter) {
1237 if (FieldIter->isUnnamedBitfield())
1238 continue;
1239
1240 if (*FieldIter == Path.back())
1241 return;
1242
1243 ++FieldIndex;
1244 }
1245
1246 assert(false && "Unable to find anonymous struct/union field");
1247}
1248
Douglas Gregor05c13a32009-01-22 00:58:24 +00001249/// @brief Check the well-formedness of a C99 designated initializer.
1250///
1251/// Determines whether the designated initializer @p DIE, which
1252/// resides at the given @p Index within the initializer list @p
1253/// IList, is well-formed for a current object of type @p DeclType
1254/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001255/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001256/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001257///
1258/// @param IList The initializer list in which this designated
1259/// initializer occurs.
1260///
Douglas Gregor71199712009-04-15 04:56:10 +00001261/// @param DIE The designated initializer expression.
1262///
1263/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001264///
1265/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1266/// into which the designation in @p DIE should refer.
1267///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001268/// @param NextField If non-NULL and the first designator in @p DIE is
1269/// a field, this will be set to the field declaration corresponding
1270/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001272/// @param NextElementIndex If non-NULL and the first designator in @p
1273/// DIE is an array designator or GNU array-range designator, this
1274/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001275///
1276/// @param Index Index into @p IList where the designated initializer
1277/// @p DIE occurs.
1278///
Douglas Gregor4c678342009-01-28 21:54:33 +00001279/// @param StructuredList The initializer list expression that
1280/// describes all of the subobject initializers in the order they'll
1281/// actually be initialized.
1282///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001283/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001284bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001285InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001286 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001287 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001288 QualType &CurrentObjectType,
1289 RecordDecl::field_iterator *NextField,
1290 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001291 unsigned &Index,
1292 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001293 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001294 bool FinishSubobjectInit,
1295 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001296 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001297 // Check the actual initialization for the designated object type.
1298 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001299
1300 // Temporarily remove the designator expression from the
1301 // initializer list that the child calls see, so that we don't try
1302 // to re-process the designator.
1303 unsigned OldIndex = Index;
1304 IList->setInit(OldIndex, DIE->getInit());
1305
1306 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001307 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001308
1309 // Restore the designated initializer expression in the syntactic
1310 // form of the initializer list.
1311 if (IList->getInit(OldIndex) != DIE->getInit())
1312 DIE->setInit(IList->getInit(OldIndex));
1313 IList->setInit(OldIndex, DIE);
1314
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001315 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001316 }
1317
Douglas Gregor71199712009-04-15 04:56:10 +00001318 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001319 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001320 "Need a non-designated initializer list to start from");
1321
Douglas Gregor71199712009-04-15 04:56:10 +00001322 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001323 // Determine the structural initializer list that corresponds to the
1324 // current subobject.
1325 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001326 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001327 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001328 SourceRange(D->getStartLocation(),
1329 DIE->getSourceRange().getEnd()));
1330 assert(StructuredList && "Expected a structured initializer list");
1331
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001332 if (D->isFieldDesignator()) {
1333 // C99 6.7.8p7:
1334 //
1335 // If a designator has the form
1336 //
1337 // . identifier
1338 //
1339 // then the current object (defined below) shall have
1340 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001341 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001342 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343 if (!RT) {
1344 SourceLocation Loc = D->getDotLoc();
1345 if (Loc.isInvalid())
1346 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001347 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1348 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001349 ++Index;
1350 return true;
1351 }
1352
Douglas Gregor4c678342009-01-28 21:54:33 +00001353 // Note: we perform a linear search of the fields here, despite
1354 // the fact that we have a faster lookup method, because we always
1355 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001356 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001357 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001358 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001359 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001360 Field = RT->getDecl()->field_begin(),
1361 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001362 for (; Field != FieldEnd; ++Field) {
1363 if (Field->isUnnamedBitfield())
1364 continue;
1365
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001366 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001367 break;
1368
1369 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001370 }
1371
Douglas Gregor4c678342009-01-28 21:54:33 +00001372 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001373 // There was no normal field in the struct with the designated
1374 // name. Perform another lookup for this name, which may find
1375 // something that we can't designate (e.g., a member function),
1376 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001377 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001378 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001379 if (Lookup.first == Lookup.second) {
1380 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001381 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001382 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001383 ++Index;
1384 return true;
1385 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1386 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1387 ->isAnonymousStructOrUnion()) {
1388 // Handle an field designator that refers to a member of an
1389 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001390 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001391 cast<FieldDecl>(*Lookup.first),
1392 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001393 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 } else {
1395 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001396 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001397 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001398 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001399 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001400 ++Index;
1401 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001402 }
1403 } else if (!KnownField &&
1404 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001406 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1407 Field, FieldIndex);
1408 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001409 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001410
1411 // All of the fields of a union are located at the same place in
1412 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001413 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001414 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001415 StructuredList->setInitializedFieldInUnion(*Field);
1416 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001417
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001418 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001419 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Douglas Gregor4c678342009-01-28 21:54:33 +00001421 // Make sure that our non-designated initializer list has space
1422 // for a subobject corresponding to this field.
1423 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001424 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001425
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001426 // This designator names a flexible array member.
1427 if (Field->getType()->isIncompleteArrayType()) {
1428 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001429 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001430 // We can't designate an object within the flexible array
1431 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001432 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001433 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001434 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001435 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001436 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001437 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001438 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001439 << *Field;
1440 Invalid = true;
1441 }
1442
1443 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1444 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001445 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001446 diag::err_flexible_array_init_needs_braces)
1447 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001448 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001449 << *Field;
1450 Invalid = true;
1451 }
1452
1453 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001454 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001455 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001456 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001457 diag::err_flexible_array_init_nonempty)
1458 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 << *Field;
1461 Invalid = true;
1462 }
1463
1464 if (Invalid) {
1465 ++Index;
1466 return true;
1467 }
1468
1469 // Initialize the array.
1470 bool prevHadError = hadError;
1471 unsigned newStructuredIndex = FieldIndex;
1472 unsigned OldIndex = Index;
1473 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001474 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001475 StructuredList, newStructuredIndex);
1476 IList->setInit(OldIndex, DIE);
1477 if (hadError && !prevHadError) {
1478 ++Field;
1479 ++FieldIndex;
1480 if (NextField)
1481 *NextField = Field;
1482 StructuredIndex = FieldIndex;
1483 return true;
1484 }
1485 } else {
1486 // Recurse to check later designated subobjects.
1487 QualType FieldType = (*Field)->getType();
1488 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001489 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1490 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 true, false))
1492 return true;
1493 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001494
1495 // Find the position of the next field to be initialized in this
1496 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001497 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001498 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001499
1500 // If this the first designator, our caller will continue checking
1501 // the rest of this struct/class/union subobject.
1502 if (IsFirstDesignator) {
1503 if (NextField)
1504 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001505 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001506 return false;
1507 }
1508
Douglas Gregor34e79462009-01-28 23:36:17 +00001509 if (!FinishSubobjectInit)
1510 return false;
1511
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001512 // We've already initialized something in the union; we're done.
1513 if (RT->getDecl()->isUnion())
1514 return hadError;
1515
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001516 // Check the remaining fields within this class/struct/union subobject.
1517 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001518 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1519 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001520 return hadError && !prevHadError;
1521 }
1522
1523 // C99 6.7.8p6:
1524 //
1525 // If a designator has the form
1526 //
1527 // [ constant-expression ]
1528 //
1529 // then the current object (defined below) shall have array
1530 // type and the expression shall be an integer constant
1531 // expression. If the array is of unknown size, any
1532 // nonnegative value is valid.
1533 //
1534 // Additionally, cope with the GNU extension that permits
1535 // designators of the form
1536 //
1537 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001538 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001539 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001540 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 << CurrentObjectType;
1542 ++Index;
1543 return true;
1544 }
1545
1546 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001547 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1548 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001549 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001550 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001551 DesignatedEndIndex = DesignatedStartIndex;
1552 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001553 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001554
Mike Stump1eb44332009-09-09 15:08:12 +00001555
1556 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001557 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001558 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001559 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001560 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001561
Chris Lattner3bf68932009-04-25 21:59:05 +00001562 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001563 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001564 }
1565
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001566 if (isa<ConstantArrayType>(AT)) {
1567 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1569 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1570 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1571 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1572 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001573 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001575 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576 << IndexExpr->getSourceRange();
1577 ++Index;
1578 return true;
1579 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001580 } else {
1581 // Make sure the bit-widths and signedness match.
1582 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1583 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001584 else if (DesignatedStartIndex.getBitWidth() <
1585 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001586 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1587 DesignatedStartIndex.setIsUnsigned(true);
1588 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor4c678342009-01-28 21:54:33 +00001591 // Make sure that our non-designated initializer list has space
1592 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001593 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001594 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001595 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001596
Douglas Gregor34e79462009-01-28 23:36:17 +00001597 // Repeatedly perform subobject initializations in the range
1598 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001599
Douglas Gregor34e79462009-01-28 23:36:17 +00001600 // Move to the next designator
1601 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1602 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001603 while (DesignatedStartIndex <= DesignatedEndIndex) {
1604 // Recurse to check later designated subobjects.
1605 QualType ElementType = AT->getElementType();
1606 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001607 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1608 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001609 (DesignatedStartIndex == DesignatedEndIndex),
1610 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001611 return true;
1612
1613 // Move to the next index in the array that we'll be initializing.
1614 ++DesignatedStartIndex;
1615 ElementIndex = DesignatedStartIndex.getZExtValue();
1616 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617
1618 // If this the first designator, our caller will continue checking
1619 // the rest of this array subobject.
1620 if (IsFirstDesignator) {
1621 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001622 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001623 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624 return false;
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregor34e79462009-01-28 23:36:17 +00001627 if (!FinishSubobjectInit)
1628 return false;
1629
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001630 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001631 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001632 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001633 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001634 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001635}
1636
Douglas Gregor4c678342009-01-28 21:54:33 +00001637// Get the structured initializer list for a subobject of type
1638// @p CurrentObjectType.
1639InitListExpr *
1640InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1641 QualType CurrentObjectType,
1642 InitListExpr *StructuredList,
1643 unsigned StructuredIndex,
1644 SourceRange InitRange) {
1645 Expr *ExistingInit = 0;
1646 if (!StructuredList)
1647 ExistingInit = SyntacticToSemantic[IList];
1648 else if (StructuredIndex < StructuredList->getNumInits())
1649 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregor4c678342009-01-28 21:54:33 +00001651 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1652 return Result;
1653
1654 if (ExistingInit) {
1655 // We are creating an initializer list that initializes the
1656 // subobjects of the current object, but there was already an
1657 // initialization that completely initialized the current
1658 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001659 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001660 // struct X { int a, b; };
1661 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001662 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001663 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1664 // designated initializer re-initializes the whole
1665 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001666 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001667 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001668 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001669 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001670 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001671 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001672 << ExistingInit->getSourceRange();
1673 }
1674
Mike Stump1eb44332009-09-09 15:08:12 +00001675 InitListExpr *Result
1676 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001677 InitRange.getEnd());
1678
Douglas Gregor4c678342009-01-28 21:54:33 +00001679 Result->setType(CurrentObjectType);
1680
Douglas Gregorfa219202009-03-20 23:58:33 +00001681 // Pre-allocate storage for the structured initializer list.
1682 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001683 unsigned NumInits = 0;
1684 if (!StructuredList)
1685 NumInits = IList->getNumInits();
1686 else if (Index < IList->getNumInits()) {
1687 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1688 NumInits = SubList->getNumInits();
1689 }
1690
Mike Stump1eb44332009-09-09 15:08:12 +00001691 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001692 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1693 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1694 NumElements = CAType->getSize().getZExtValue();
1695 // Simple heuristic so that we don't allocate a very large
1696 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001697 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001698 NumElements = 0;
1699 }
John McCall183700f2009-09-21 23:43:11 +00001700 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001701 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001702 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001703 RecordDecl *RDecl = RType->getDecl();
1704 if (RDecl->isUnion())
1705 NumElements = 1;
1706 else
Mike Stump1eb44332009-09-09 15:08:12 +00001707 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001708 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001709 }
1710
Douglas Gregor08457732009-03-21 18:13:52 +00001711 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001712 NumElements = IList->getNumInits();
1713
1714 Result->reserveInits(NumElements);
1715
Douglas Gregor4c678342009-01-28 21:54:33 +00001716 // Link this new initializer list into the structured initializer
1717 // lists.
1718 if (StructuredList)
1719 StructuredList->updateInit(StructuredIndex, Result);
1720 else {
1721 Result->setSyntacticForm(IList);
1722 SyntacticToSemantic[IList] = Result;
1723 }
1724
1725 return Result;
1726}
1727
1728/// Update the initializer at index @p StructuredIndex within the
1729/// structured initializer list to the value @p expr.
1730void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1731 unsigned &StructuredIndex,
1732 Expr *expr) {
1733 // No structured initializer list to update
1734 if (!StructuredList)
1735 return;
1736
1737 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1738 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001739 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001740 diag::warn_initializer_overrides)
1741 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001742 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001743 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001744 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001745 << PrevInit->getSourceRange();
1746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Douglas Gregor4c678342009-01-28 21:54:33 +00001748 ++StructuredIndex;
1749}
1750
Douglas Gregor05c13a32009-01-22 00:58:24 +00001751/// Check that the given Index expression is a valid array designator
1752/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001753/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001754/// and produces a reasonable diagnostic if there is a
1755/// failure. Returns true if there was an error, false otherwise. If
1756/// everything went okay, Value will receive the value of the constant
1757/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001758static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001759CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001760 SourceLocation Loc = Index->getSourceRange().getBegin();
1761
1762 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001763 if (S.VerifyIntegerConstantExpression(Index, &Value))
1764 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001765
Chris Lattner3bf68932009-04-25 21:59:05 +00001766 if (Value.isSigned() && Value.isNegative())
1767 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001768 << Value.toString(10) << Index->getSourceRange();
1769
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001770 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001771 return false;
1772}
1773
1774Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1775 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001776 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001777 OwningExprResult Init) {
1778 typedef DesignatedInitExpr::Designator ASTDesignator;
1779
1780 bool Invalid = false;
1781 llvm::SmallVector<ASTDesignator, 32> Designators;
1782 llvm::SmallVector<Expr *, 32> InitExpressions;
1783
1784 // Build designators and check array designator expressions.
1785 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1786 const Designator &D = Desig.getDesignator(Idx);
1787 switch (D.getKind()) {
1788 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001789 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001790 D.getFieldLoc()));
1791 break;
1792
1793 case Designator::ArrayDesignator: {
1794 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1795 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001796 if (!Index->isTypeDependent() &&
1797 !Index->isValueDependent() &&
1798 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001799 Invalid = true;
1800 else {
1801 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001802 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001803 D.getRBracketLoc()));
1804 InitExpressions.push_back(Index);
1805 }
1806 break;
1807 }
1808
1809 case Designator::ArrayRangeDesignator: {
1810 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1811 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1812 llvm::APSInt StartValue;
1813 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001814 bool StartDependent = StartIndex->isTypeDependent() ||
1815 StartIndex->isValueDependent();
1816 bool EndDependent = EndIndex->isTypeDependent() ||
1817 EndIndex->isValueDependent();
1818 if ((!StartDependent &&
1819 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1820 (!EndDependent &&
1821 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001822 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001823 else {
1824 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001825 if (StartDependent || EndDependent) {
1826 // Nothing to compute.
1827 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001828 EndValue.extend(StartValue.getBitWidth());
1829 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1830 StartValue.extend(EndValue.getBitWidth());
1831
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001832 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001833 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001834 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001835 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1836 Invalid = true;
1837 } else {
1838 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001839 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001840 D.getEllipsisLoc(),
1841 D.getRBracketLoc()));
1842 InitExpressions.push_back(StartIndex);
1843 InitExpressions.push_back(EndIndex);
1844 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001845 }
1846 break;
1847 }
1848 }
1849 }
1850
1851 if (Invalid || Init.isInvalid())
1852 return ExprError();
1853
1854 // Clear out the expressions within the designation.
1855 Desig.ClearExprs(*this);
1856
1857 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001858 = DesignatedInitExpr::Create(Context,
1859 Designators.data(), Designators.size(),
1860 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001861 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001862 return Owned(DIE);
1863}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001864
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001865bool Sema::CheckInitList(const InitializedEntity &Entity,
1866 InitListExpr *&InitList, QualType &DeclType) {
1867 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001868 if (!CheckInitList.HadError())
1869 InitList = CheckInitList.getFullyStructuredList();
1870
1871 return CheckInitList.HadError();
1872}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001873
Douglas Gregor20093b42009-12-09 23:02:17 +00001874//===----------------------------------------------------------------------===//
1875// Initialization entity
1876//===----------------------------------------------------------------------===//
1877
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001878InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1879 const InitializedEntity &Parent)
1880 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1881{
1882 if (isa<ArrayType>(Parent.TL.getType())) {
1883 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1884 return;
1885 }
1886
1887 // FIXME: should be able to get type location information for vectors, too.
1888
1889 QualType T;
1890 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1891 T = AT->getElementType();
1892 else
1893 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1894
1895 // FIXME: Once we've gone through the effort to create the fake
1896 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1897 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1898 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1899 TL = DI->getTypeLoc();
1900}
1901
Douglas Gregor20093b42009-12-09 23:02:17 +00001902void InitializedEntity::InitDeclLoc() {
1903 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1904 "InitDeclLoc cannot be used with non-declaration entities.");
1905
1906 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1907 TL = DI->getTypeLoc();
1908 return;
1909 }
1910
1911 // FIXME: Once we've gone through the effort to create the fake
1912 // TypeSourceInfo, should we cache it in the declaration?
1913 // (If not, we "leak" it).
1914 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1915 .CreateTypeSourceInfo(VariableOrMember->getType());
1916 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1917 TL = DI->getTypeLoc();
1918}
1919
1920InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1921 CXXBaseSpecifier *Base)
1922{
1923 InitializedEntity Result;
1924 Result.Kind = EK_Base;
1925 Result.Base = Base;
1926 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1927 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1928 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1929 Result.TL = DI->getTypeLoc();
1930 return Result;
1931}
1932
Douglas Gregor99a2e602009-12-16 01:38:02 +00001933DeclarationName InitializedEntity::getName() const {
1934 switch (getKind()) {
1935 case EK_Variable:
1936 case EK_Parameter:
1937 case EK_Member:
1938 return VariableOrMember->getDeclName();
1939
1940 case EK_Result:
1941 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001942 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001943 case EK_Temporary:
1944 case EK_Base:
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001945 case EK_ArrayOrVectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001946 return DeclarationName();
1947 }
1948
1949 // Silence GCC warning
1950 return DeclarationName();
1951}
1952
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001953DeclaratorDecl *InitializedEntity::getDecl() const {
1954 switch (getKind()) {
1955 case EK_Variable:
1956 case EK_Parameter:
1957 case EK_Member:
1958 return VariableOrMember;
1959
1960 case EK_Result:
1961 case EK_Exception:
1962 case EK_New:
1963 case EK_Temporary:
1964 case EK_Base:
1965 case EK_ArrayOrVectorElement:
1966 return 0;
1967 }
1968
1969 // Silence GCC warning
1970 return 0;
1971}
1972
Douglas Gregor20093b42009-12-09 23:02:17 +00001973//===----------------------------------------------------------------------===//
1974// Initialization sequence
1975//===----------------------------------------------------------------------===//
1976
1977void InitializationSequence::Step::Destroy() {
1978 switch (Kind) {
1979 case SK_ResolveAddressOfOverloadedFunction:
1980 case SK_CastDerivedToBaseRValue:
1981 case SK_CastDerivedToBaseLValue:
1982 case SK_BindReference:
1983 case SK_BindReferenceToTemporary:
1984 case SK_UserConversion:
1985 case SK_QualificationConversionRValue:
1986 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001987 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001988 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001989 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001990 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001991 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001992 break;
1993
1994 case SK_ConversionSequence:
1995 delete ICS;
1996 }
1997}
1998
1999void InitializationSequence::AddAddressOverloadResolutionStep(
2000 FunctionDecl *Function) {
2001 Step S;
2002 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2003 S.Type = Function->getType();
2004 S.Function = Function;
2005 Steps.push_back(S);
2006}
2007
2008void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2009 bool IsLValue) {
2010 Step S;
2011 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2012 S.Type = BaseType;
2013 Steps.push_back(S);
2014}
2015
2016void InitializationSequence::AddReferenceBindingStep(QualType T,
2017 bool BindingTemporary) {
2018 Step S;
2019 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2020 S.Type = T;
2021 Steps.push_back(S);
2022}
2023
Eli Friedman03981012009-12-11 02:42:07 +00002024void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2025 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002026 Step S;
2027 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002028 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002029 S.Function = Function;
2030 Steps.push_back(S);
2031}
2032
2033void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2034 bool IsLValue) {
2035 Step S;
2036 S.Kind = IsLValue? SK_QualificationConversionLValue
2037 : SK_QualificationConversionRValue;
2038 S.Type = Ty;
2039 Steps.push_back(S);
2040}
2041
2042void InitializationSequence::AddConversionSequenceStep(
2043 const ImplicitConversionSequence &ICS,
2044 QualType T) {
2045 Step S;
2046 S.Kind = SK_ConversionSequence;
2047 S.Type = T;
2048 S.ICS = new ImplicitConversionSequence(ICS);
2049 Steps.push_back(S);
2050}
2051
Douglas Gregord87b61f2009-12-10 17:56:55 +00002052void InitializationSequence::AddListInitializationStep(QualType T) {
2053 Step S;
2054 S.Kind = SK_ListInitialization;
2055 S.Type = T;
2056 Steps.push_back(S);
2057}
2058
Douglas Gregor51c56d62009-12-14 20:49:26 +00002059void
2060InitializationSequence::AddConstructorInitializationStep(
2061 CXXConstructorDecl *Constructor,
2062 QualType T) {
2063 Step S;
2064 S.Kind = SK_ConstructorInitialization;
2065 S.Type = T;
2066 S.Function = Constructor;
2067 Steps.push_back(S);
2068}
2069
Douglas Gregor71d17402009-12-15 00:01:57 +00002070void InitializationSequence::AddZeroInitializationStep(QualType T) {
2071 Step S;
2072 S.Kind = SK_ZeroInitialization;
2073 S.Type = T;
2074 Steps.push_back(S);
2075}
2076
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002077void InitializationSequence::AddCAssignmentStep(QualType T) {
2078 Step S;
2079 S.Kind = SK_CAssignment;
2080 S.Type = T;
2081 Steps.push_back(S);
2082}
2083
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002084void InitializationSequence::AddStringInitStep(QualType T) {
2085 Step S;
2086 S.Kind = SK_StringInit;
2087 S.Type = T;
2088 Steps.push_back(S);
2089}
2090
Douglas Gregor20093b42009-12-09 23:02:17 +00002091void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2092 OverloadingResult Result) {
2093 SequenceKind = FailedSequence;
2094 this->Failure = Failure;
2095 this->FailedOverloadResult = Result;
2096}
2097
2098//===----------------------------------------------------------------------===//
2099// Attempt initialization
2100//===----------------------------------------------------------------------===//
2101
2102/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002103static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002104 const InitializedEntity &Entity,
2105 const InitializationKind &Kind,
2106 InitListExpr *InitList,
2107 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002108 // FIXME: We only perform rudimentary checking of list
2109 // initializations at this point, then assume that any list
2110 // initialization of an array, aggregate, or scalar will be
2111 // well-formed. We we actually "perform" list initialization, we'll
2112 // do all of the necessary checking. C++0x initializer lists will
2113 // force us to perform more checking here.
2114 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2115
2116 QualType DestType = Entity.getType().getType();
2117
2118 // C++ [dcl.init]p13:
2119 // If T is a scalar type, then a declaration of the form
2120 //
2121 // T x = { a };
2122 //
2123 // is equivalent to
2124 //
2125 // T x = a;
2126 if (DestType->isScalarType()) {
2127 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2128 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2129 return;
2130 }
2131
2132 // Assume scalar initialization from a single value works.
2133 } else if (DestType->isAggregateType()) {
2134 // Assume aggregate initialization works.
2135 } else if (DestType->isVectorType()) {
2136 // Assume vector initialization works.
2137 } else if (DestType->isReferenceType()) {
2138 // FIXME: C++0x defines behavior for this.
2139 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2140 return;
2141 } else if (DestType->isRecordType()) {
2142 // FIXME: C++0x defines behavior for this
2143 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2144 }
2145
2146 // Add a general "list initialization" step.
2147 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002148}
2149
2150/// \brief Try a reference initialization that involves calling a conversion
2151/// function.
2152///
2153/// FIXME: look intos DRs 656, 896
2154static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2155 const InitializedEntity &Entity,
2156 const InitializationKind &Kind,
2157 Expr *Initializer,
2158 bool AllowRValues,
2159 InitializationSequence &Sequence) {
2160 QualType DestType = Entity.getType().getType();
2161 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2162 QualType T1 = cv1T1.getUnqualifiedType();
2163 QualType cv2T2 = Initializer->getType();
2164 QualType T2 = cv2T2.getUnqualifiedType();
2165
2166 bool DerivedToBase;
2167 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2168 T1, T2, DerivedToBase) &&
2169 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002170 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002171
2172 // Build the candidate set directly in the initialization sequence
2173 // structure, so that it will persist if we fail.
2174 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2175 CandidateSet.clear();
2176
2177 // Determine whether we are allowed to call explicit constructors or
2178 // explicit conversion operators.
2179 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2180
2181 const RecordType *T1RecordType = 0;
2182 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2183 // The type we're converting to is a class type. Enumerate its constructors
2184 // to see if there is a suitable conversion.
2185 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2186
2187 DeclarationName ConstructorName
2188 = S.Context.DeclarationNames.getCXXConstructorName(
2189 S.Context.getCanonicalType(T1).getUnqualifiedType());
2190 DeclContext::lookup_iterator Con, ConEnd;
2191 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2192 Con != ConEnd; ++Con) {
2193 // Find the constructor (which may be a template).
2194 CXXConstructorDecl *Constructor = 0;
2195 FunctionTemplateDecl *ConstructorTmpl
2196 = dyn_cast<FunctionTemplateDecl>(*Con);
2197 if (ConstructorTmpl)
2198 Constructor = cast<CXXConstructorDecl>(
2199 ConstructorTmpl->getTemplatedDecl());
2200 else
2201 Constructor = cast<CXXConstructorDecl>(*Con);
2202
2203 if (!Constructor->isInvalidDecl() &&
2204 Constructor->isConvertingConstructor(AllowExplicit)) {
2205 if (ConstructorTmpl)
2206 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2207 &Initializer, 1, CandidateSet);
2208 else
2209 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2210 }
2211 }
2212 }
2213
2214 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2215 // The type we're converting from is a class type, enumerate its conversion
2216 // functions.
2217 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2218
2219 // Determine the type we are converting to. If we are allowed to
2220 // convert to an rvalue, take the type that the destination type
2221 // refers to.
2222 QualType ToType = AllowRValues? cv1T1 : DestType;
2223
2224 const UnresolvedSet *Conversions
2225 = T2RecordDecl->getVisibleConversionFunctions();
2226 for (UnresolvedSet::iterator I = Conversions->begin(),
2227 E = Conversions->end();
2228 I != E; ++I) {
2229 NamedDecl *D = *I;
2230 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2231 if (isa<UsingShadowDecl>(D))
2232 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2233
2234 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2235 CXXConversionDecl *Conv;
2236 if (ConvTemplate)
2237 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2238 else
2239 Conv = cast<CXXConversionDecl>(*I);
2240
2241 // If the conversion function doesn't return a reference type,
2242 // it can't be considered for this conversion unless we're allowed to
2243 // consider rvalues.
2244 // FIXME: Do we need to make sure that we only consider conversion
2245 // candidates with reference-compatible results? That might be needed to
2246 // break recursion.
2247 if ((AllowExplicit || !Conv->isExplicit()) &&
2248 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2249 if (ConvTemplate)
2250 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2251 ToType, CandidateSet);
2252 else
2253 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2254 CandidateSet);
2255 }
2256 }
2257 }
2258
2259 SourceLocation DeclLoc = Initializer->getLocStart();
2260
2261 // Perform overload resolution. If it fails, return the failed result.
2262 OverloadCandidateSet::iterator Best;
2263 if (OverloadingResult Result
2264 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2265 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002266
Douglas Gregor20093b42009-12-09 23:02:17 +00002267 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002268
2269 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002270 if (isa<CXXConversionDecl>(Function))
2271 T2 = Function->getResultType();
2272 else
2273 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002274
2275 // Add the user-defined conversion step.
2276 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2277
2278 // Determine whether we need to perform derived-to-base or
2279 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002280 bool NewDerivedToBase = false;
2281 Sema::ReferenceCompareResult NewRefRelationship
2282 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2283 NewDerivedToBase);
2284 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2285 "Overload resolution picked a bad conversion function");
2286 (void)NewRefRelationship;
2287 if (NewDerivedToBase)
2288 Sequence.AddDerivedToBaseCastStep(
2289 S.Context.getQualifiedType(T1,
2290 T2.getNonReferenceType().getQualifiers()),
2291 /*isLValue=*/true);
2292
2293 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2294 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2295
2296 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2297 return OR_Success;
2298}
2299
2300/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2301static void TryReferenceInitialization(Sema &S,
2302 const InitializedEntity &Entity,
2303 const InitializationKind &Kind,
2304 Expr *Initializer,
2305 InitializationSequence &Sequence) {
2306 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2307
2308 QualType DestType = Entity.getType().getType();
2309 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2310 QualType T1 = cv1T1.getUnqualifiedType();
2311 QualType cv2T2 = Initializer->getType();
2312 QualType T2 = cv2T2.getUnqualifiedType();
2313 SourceLocation DeclLoc = Initializer->getLocStart();
2314
2315 // If the initializer is the address of an overloaded function, try
2316 // to resolve the overloaded function. If all goes well, T2 is the
2317 // type of the resulting function.
2318 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2319 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2320 T1,
2321 false);
2322 if (!Fn) {
2323 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2324 return;
2325 }
2326
2327 Sequence.AddAddressOverloadResolutionStep(Fn);
2328 cv2T2 = Fn->getType();
2329 T2 = cv2T2.getUnqualifiedType();
2330 }
2331
2332 // FIXME: Rvalue references
2333 bool ForceRValue = false;
2334
2335 // Compute some basic properties of the types and the initializer.
2336 bool isLValueRef = DestType->isLValueReferenceType();
2337 bool isRValueRef = !isLValueRef;
2338 bool DerivedToBase = false;
2339 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2340 Initializer->isLvalue(S.Context);
2341 Sema::ReferenceCompareResult RefRelationship
2342 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2343
2344 // C++0x [dcl.init.ref]p5:
2345 // A reference to type "cv1 T1" is initialized by an expression of type
2346 // "cv2 T2" as follows:
2347 //
2348 // - If the reference is an lvalue reference and the initializer
2349 // expression
2350 OverloadingResult ConvOvlResult = OR_Success;
2351 if (isLValueRef) {
2352 if (InitLvalue == Expr::LV_Valid &&
2353 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2354 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2355 // reference-compatible with "cv2 T2," or
2356 //
2357 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2358 // bit-field when we're determining whether the reference initialization
2359 // can occur. This property will be checked by PerformInitialization.
2360 if (DerivedToBase)
2361 Sequence.AddDerivedToBaseCastStep(
2362 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2363 /*isLValue=*/true);
2364 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2365 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2366 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2367 return;
2368 }
2369
2370 // - has a class type (i.e., T2 is a class type), where T1 is not
2371 // reference-related to T2, and can be implicitly converted to an
2372 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2373 // with "cv3 T3" (this conversion is selected by enumerating the
2374 // applicable conversion functions (13.3.1.6) and choosing the best
2375 // one through overload resolution (13.3)),
2376 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2377 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2378 Initializer,
2379 /*AllowRValues=*/false,
2380 Sequence);
2381 if (ConvOvlResult == OR_Success)
2382 return;
2383 }
2384 }
2385
2386 // - Otherwise, the reference shall be an lvalue reference to a
2387 // non-volatile const type (i.e., cv1 shall be const), or the reference
2388 // shall be an rvalue reference and the initializer expression shall
2389 // be an rvalue.
2390 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2391 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2392 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2393 Sequence.SetOverloadFailure(
2394 InitializationSequence::FK_ReferenceInitOverloadFailed,
2395 ConvOvlResult);
2396 else if (isLValueRef)
2397 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2398 ? (RefRelationship == Sema::Ref_Related
2399 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2400 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2401 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2402 else
2403 Sequence.SetFailed(
2404 InitializationSequence::FK_RValueReferenceBindingToLValue);
2405
2406 return;
2407 }
2408
2409 // - If T1 and T2 are class types and
2410 if (T1->isRecordType() && T2->isRecordType()) {
2411 // - the initializer expression is an rvalue and "cv1 T1" is
2412 // reference-compatible with "cv2 T2", or
2413 if (InitLvalue != Expr::LV_Valid &&
2414 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2415 if (DerivedToBase)
2416 Sequence.AddDerivedToBaseCastStep(
2417 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2418 /*isLValue=*/false);
2419 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2420 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2421 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2422 return;
2423 }
2424
2425 // - T1 is not reference-related to T2 and the initializer expression
2426 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2427 // conversion is selected by enumerating the applicable conversion
2428 // functions (13.3.1.6) and choosing the best one through overload
2429 // resolution (13.3)),
2430 if (RefRelationship == Sema::Ref_Incompatible) {
2431 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2432 Kind, Initializer,
2433 /*AllowRValues=*/true,
2434 Sequence);
2435 if (ConvOvlResult)
2436 Sequence.SetOverloadFailure(
2437 InitializationSequence::FK_ReferenceInitOverloadFailed,
2438 ConvOvlResult);
2439
2440 return;
2441 }
2442
2443 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2444 return;
2445 }
2446
2447 // - If the initializer expression is an rvalue, with T2 an array type,
2448 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2449 // is bound to the object represented by the rvalue (see 3.10).
2450 // FIXME: How can an array type be reference-compatible with anything?
2451 // Don't we mean the element types of T1 and T2?
2452
2453 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2454 // from the initializer expression using the rules for a non-reference
2455 // copy initialization (8.5). The reference is then bound to the
2456 // temporary. [...]
2457 // Determine whether we are allowed to call explicit constructors or
2458 // explicit conversion operators.
2459 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2460 ImplicitConversionSequence ICS
2461 = S.TryImplicitConversion(Initializer, cv1T1,
2462 /*SuppressUserConversions=*/false, AllowExplicit,
2463 /*ForceRValue=*/false,
2464 /*FIXME:InOverloadResolution=*/false,
2465 /*UserCast=*/Kind.isExplicitCast());
2466
2467 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2468 // FIXME: Use the conversion function set stored in ICS to turn
2469 // this into an overloading ambiguity diagnostic. However, we need
2470 // to keep that set as an OverloadCandidateSet rather than as some
2471 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002472 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2473 Sequence.SetOverloadFailure(
2474 InitializationSequence::FK_ReferenceInitOverloadFailed,
2475 ConvOvlResult);
2476 else
2477 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002478 return;
2479 }
2480
2481 // [...] If T1 is reference-related to T2, cv1 must be the
2482 // same cv-qualification as, or greater cv-qualification
2483 // than, cv2; otherwise, the program is ill-formed.
2484 if (RefRelationship == Sema::Ref_Related &&
2485 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2486 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2487 return;
2488 }
2489
2490 // Perform the actual conversion.
2491 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2492 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2493 return;
2494}
2495
2496/// \brief Attempt character array initialization from a string literal
2497/// (C++ [dcl.init.string], C99 6.7.8).
2498static void TryStringLiteralInitialization(Sema &S,
2499 const InitializedEntity &Entity,
2500 const InitializationKind &Kind,
2501 Expr *Initializer,
2502 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002503 Sequence.setSequenceKind(InitializationSequence::StringInit);
2504 Sequence.AddStringInitStep(Entity.getType().getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002505}
2506
Douglas Gregor20093b42009-12-09 23:02:17 +00002507/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2508/// enumerates the constructors of the initialized entity and performs overload
2509/// resolution to select the best.
2510static void TryConstructorInitialization(Sema &S,
2511 const InitializedEntity &Entity,
2512 const InitializationKind &Kind,
2513 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002514 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002515 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002516 if (Kind.getKind() == InitializationKind::IK_Copy)
2517 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2518 else
2519 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002520
2521 // Build the candidate set directly in the initialization sequence
2522 // structure, so that it will persist if we fail.
2523 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2524 CandidateSet.clear();
2525
2526 // Determine whether we are allowed to call explicit constructors or
2527 // explicit conversion operators.
2528 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2529 Kind.getKind() == InitializationKind::IK_Value ||
2530 Kind.getKind() == InitializationKind::IK_Default);
2531
2532 // The type we're converting to is a class type. Enumerate its constructors
2533 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002534 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2535 assert(DestRecordType && "Constructor initialization requires record type");
2536 CXXRecordDecl *DestRecordDecl
2537 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2538
2539 DeclarationName ConstructorName
2540 = S.Context.DeclarationNames.getCXXConstructorName(
2541 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2542 DeclContext::lookup_iterator Con, ConEnd;
2543 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2544 Con != ConEnd; ++Con) {
2545 // Find the constructor (which may be a template).
2546 CXXConstructorDecl *Constructor = 0;
2547 FunctionTemplateDecl *ConstructorTmpl
2548 = dyn_cast<FunctionTemplateDecl>(*Con);
2549 if (ConstructorTmpl)
2550 Constructor = cast<CXXConstructorDecl>(
2551 ConstructorTmpl->getTemplatedDecl());
2552 else
2553 Constructor = cast<CXXConstructorDecl>(*Con);
2554
2555 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002556 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002557 if (ConstructorTmpl)
2558 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2559 Args, NumArgs, CandidateSet);
2560 else
2561 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2562 }
2563 }
2564
2565 SourceLocation DeclLoc = Kind.getLocation();
2566
2567 // Perform overload resolution. If it fails, return the failed result.
2568 OverloadCandidateSet::iterator Best;
2569 if (OverloadingResult Result
2570 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2571 Sequence.SetOverloadFailure(
2572 InitializationSequence::FK_ConstructorOverloadFailed,
2573 Result);
2574 return;
2575 }
2576
2577 // Add the constructor initialization step. Any cv-qualification conversion is
2578 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002579 if (Kind.getKind() == InitializationKind::IK_Copy) {
2580 Sequence.AddUserConversionStep(Best->Function, DestType);
2581 } else {
2582 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002583 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002584 DestType);
2585 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002586}
2587
Douglas Gregor71d17402009-12-15 00:01:57 +00002588/// \brief Attempt value initialization (C++ [dcl.init]p7).
2589static void TryValueInitialization(Sema &S,
2590 const InitializedEntity &Entity,
2591 const InitializationKind &Kind,
2592 InitializationSequence &Sequence) {
2593 // C++ [dcl.init]p5:
2594 //
2595 // To value-initialize an object of type T means:
2596 QualType T = Entity.getType().getType();
2597
2598 // -- if T is an array type, then each element is value-initialized;
2599 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2600 T = AT->getElementType();
2601
2602 if (const RecordType *RT = T->getAs<RecordType>()) {
2603 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2604 // -- if T is a class type (clause 9) with a user-declared
2605 // constructor (12.1), then the default constructor for T is
2606 // called (and the initialization is ill-formed if T has no
2607 // accessible default constructor);
2608 //
2609 // FIXME: we really want to refer to a single subobject of the array,
2610 // but Entity doesn't have a way to capture that (yet).
2611 if (ClassDecl->hasUserDeclaredConstructor())
2612 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2613
Douglas Gregor16006c92009-12-16 18:50:27 +00002614 // -- if T is a (possibly cv-qualified) non-union class type
2615 // without a user-provided constructor, then the object is
2616 // zero-initialized and, if T’s implicitly-declared default
2617 // constructor is non-trivial, that constructor is called.
2618 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2619 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2620 !ClassDecl->hasTrivialConstructor()) {
2621 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2622 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2623 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002624 }
2625 }
2626
2627 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2628 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2629}
2630
Douglas Gregor99a2e602009-12-16 01:38:02 +00002631/// \brief Attempt default initialization (C++ [dcl.init]p6).
2632static void TryDefaultInitialization(Sema &S,
2633 const InitializedEntity &Entity,
2634 const InitializationKind &Kind,
2635 InitializationSequence &Sequence) {
2636 assert(Kind.getKind() == InitializationKind::IK_Default);
2637
2638 // C++ [dcl.init]p6:
2639 // To default-initialize an object of type T means:
2640 // - if T is an array type, each element is default-initialized;
2641 QualType DestType = Entity.getType().getType();
2642 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2643 DestType = Array->getElementType();
2644
2645 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2646 // constructor for T is called (and the initialization is ill-formed if
2647 // T has no accessible default constructor);
2648 if (DestType->isRecordType()) {
2649 // FIXME: If a program calls for the default initialization of an object of
2650 // a const-qualified type T, T shall be a class type with a user-provided
2651 // default constructor.
2652 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2653 Sequence);
2654 }
2655
2656 // - otherwise, no initialization is performed.
2657 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2658
2659 // If a program calls for the default initialization of an object of
2660 // a const-qualified type T, T shall be a class type with a user-provided
2661 // default constructor.
2662 if (DestType.isConstQualified())
2663 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2664}
2665
Douglas Gregor20093b42009-12-09 23:02:17 +00002666/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2667/// which enumerates all conversion functions and performs overload resolution
2668/// to select the best.
2669static void TryUserDefinedConversion(Sema &S,
2670 const InitializedEntity &Entity,
2671 const InitializationKind &Kind,
2672 Expr *Initializer,
2673 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002674 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2675
2676 QualType DestType = Entity.getType().getType();
2677 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2678 QualType SourceType = Initializer->getType();
2679 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2680 "Must have a class type to perform a user-defined conversion");
2681
2682 // Build the candidate set directly in the initialization sequence
2683 // structure, so that it will persist if we fail.
2684 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2685 CandidateSet.clear();
2686
2687 // Determine whether we are allowed to call explicit constructors or
2688 // explicit conversion operators.
2689 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2690
2691 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2692 // The type we're converting to is a class type. Enumerate its constructors
2693 // to see if there is a suitable conversion.
2694 CXXRecordDecl *DestRecordDecl
2695 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2696
2697 DeclarationName ConstructorName
2698 = S.Context.DeclarationNames.getCXXConstructorName(
2699 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2700 DeclContext::lookup_iterator Con, ConEnd;
2701 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2702 Con != ConEnd; ++Con) {
2703 // Find the constructor (which may be a template).
2704 CXXConstructorDecl *Constructor = 0;
2705 FunctionTemplateDecl *ConstructorTmpl
2706 = dyn_cast<FunctionTemplateDecl>(*Con);
2707 if (ConstructorTmpl)
2708 Constructor = cast<CXXConstructorDecl>(
2709 ConstructorTmpl->getTemplatedDecl());
2710 else
2711 Constructor = cast<CXXConstructorDecl>(*Con);
2712
2713 if (!Constructor->isInvalidDecl() &&
2714 Constructor->isConvertingConstructor(AllowExplicit)) {
2715 if (ConstructorTmpl)
2716 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2717 &Initializer, 1, CandidateSet);
2718 else
2719 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2720 }
2721 }
2722 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002723
2724 SourceLocation DeclLoc = Initializer->getLocStart();
2725
Douglas Gregor4a520a22009-12-14 17:27:33 +00002726 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2727 // The type we're converting from is a class type, enumerate its conversion
2728 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002729
2730 // Try to force the type to be complete before enumerating the conversion
2731 // functions; it's okay if this fails, though.
2732 S.RequireCompleteType(DeclLoc, SourceType, 0);
2733
Douglas Gregor4a520a22009-12-14 17:27:33 +00002734 CXXRecordDecl *SourceRecordDecl
2735 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2736
2737 const UnresolvedSet *Conversions
2738 = SourceRecordDecl->getVisibleConversionFunctions();
2739 for (UnresolvedSet::iterator I = Conversions->begin(),
2740 E = Conversions->end();
2741 I != E; ++I) {
2742 NamedDecl *D = *I;
2743 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2744 if (isa<UsingShadowDecl>(D))
2745 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2746
2747 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2748 CXXConversionDecl *Conv;
2749 if (ConvTemplate)
2750 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2751 else
2752 Conv = cast<CXXConversionDecl>(*I);
2753
2754 if (AllowExplicit || !Conv->isExplicit()) {
2755 if (ConvTemplate)
2756 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2757 DestType, CandidateSet);
2758 else
2759 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2760 CandidateSet);
2761 }
2762 }
2763 }
2764
Douglas Gregor4a520a22009-12-14 17:27:33 +00002765 // Perform overload resolution. If it fails, return the failed result.
2766 OverloadCandidateSet::iterator Best;
2767 if (OverloadingResult Result
2768 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2769 Sequence.SetOverloadFailure(
2770 InitializationSequence::FK_UserConversionOverloadFailed,
2771 Result);
2772 return;
2773 }
2774
2775 FunctionDecl *Function = Best->Function;
2776
2777 if (isa<CXXConstructorDecl>(Function)) {
2778 // Add the user-defined conversion step. Any cv-qualification conversion is
2779 // subsumed by the initialization.
2780 Sequence.AddUserConversionStep(Function, DestType);
2781 return;
2782 }
2783
2784 // Add the user-defined conversion step that calls the conversion function.
2785 QualType ConvType = Function->getResultType().getNonReferenceType();
2786 Sequence.AddUserConversionStep(Function, ConvType);
2787
2788 // If the conversion following the call to the conversion function is
2789 // interesting, add it as a separate step.
2790 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2791 Best->FinalConversion.Third) {
2792 ImplicitConversionSequence ICS;
2793 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2794 ICS.Standard = Best->FinalConversion;
2795 Sequence.AddConversionSequenceStep(ICS, DestType);
2796 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002797}
2798
2799/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2800/// non-class type to another.
2801static void TryImplicitConversion(Sema &S,
2802 const InitializedEntity &Entity,
2803 const InitializationKind &Kind,
2804 Expr *Initializer,
2805 InitializationSequence &Sequence) {
2806 ImplicitConversionSequence ICS
2807 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2808 /*SuppressUserConversions=*/true,
2809 /*AllowExplicit=*/false,
2810 /*ForceRValue=*/false,
2811 /*FIXME:InOverloadResolution=*/false,
2812 /*UserCast=*/Kind.isExplicitCast());
2813
2814 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2815 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2816 return;
2817 }
2818
2819 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2820}
2821
2822InitializationSequence::InitializationSequence(Sema &S,
2823 const InitializedEntity &Entity,
2824 const InitializationKind &Kind,
2825 Expr **Args,
2826 unsigned NumArgs) {
2827 ASTContext &Context = S.Context;
2828
2829 // C++0x [dcl.init]p16:
2830 // The semantics of initializers are as follows. The destination type is
2831 // the type of the object or reference being initialized and the source
2832 // type is the type of the initializer expression. The source type is not
2833 // defined when the initializer is a braced-init-list or when it is a
2834 // parenthesized list of expressions.
2835 QualType DestType = Entity.getType().getType();
2836
2837 if (DestType->isDependentType() ||
2838 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2839 SequenceKind = DependentSequence;
2840 return;
2841 }
2842
2843 QualType SourceType;
2844 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002845 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002846 Initializer = Args[0];
2847 if (!isa<InitListExpr>(Initializer))
2848 SourceType = Initializer->getType();
2849 }
2850
2851 // - If the initializer is a braced-init-list, the object is
2852 // list-initialized (8.5.4).
2853 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2854 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002855 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002856 }
2857
2858 // - If the destination type is a reference type, see 8.5.3.
2859 if (DestType->isReferenceType()) {
2860 // C++0x [dcl.init.ref]p1:
2861 // A variable declared to be a T& or T&&, that is, "reference to type T"
2862 // (8.3.2), shall be initialized by an object, or function, of type T or
2863 // by an object that can be converted into a T.
2864 // (Therefore, multiple arguments are not permitted.)
2865 if (NumArgs != 1)
2866 SetFailed(FK_TooManyInitsForReference);
2867 else
2868 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2869 return;
2870 }
2871
2872 // - If the destination type is an array of characters, an array of
2873 // char16_t, an array of char32_t, or an array of wchar_t, and the
2874 // initializer is a string literal, see 8.5.2.
2875 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2876 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2877 return;
2878 }
2879
2880 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002881 if (Kind.getKind() == InitializationKind::IK_Value ||
2882 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002883 TryValueInitialization(S, Entity, Kind, *this);
2884 return;
2885 }
2886
Douglas Gregor99a2e602009-12-16 01:38:02 +00002887 // Handle default initialization.
2888 if (Kind.getKind() == InitializationKind::IK_Default){
2889 TryDefaultInitialization(S, Entity, Kind, *this);
2890 return;
2891 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002892
Douglas Gregor20093b42009-12-09 23:02:17 +00002893 // - Otherwise, if the destination type is an array, the program is
2894 // ill-formed.
2895 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2896 if (AT->getElementType()->isAnyCharacterType())
2897 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2898 else
2899 SetFailed(FK_ArrayNeedsInitList);
2900
2901 return;
2902 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002903
2904 // Handle initialization in C
2905 if (!S.getLangOptions().CPlusPlus) {
2906 setSequenceKind(CAssignment);
2907 AddCAssignmentStep(DestType);
2908 return;
2909 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002910
2911 // - If the destination type is a (possibly cv-qualified) class type:
2912 if (DestType->isRecordType()) {
2913 // - If the initialization is direct-initialization, or if it is
2914 // copy-initialization where the cv-unqualified version of the
2915 // source type is the same class as, or a derived class of, the
2916 // class of the destination, constructors are considered. [...]
2917 if (Kind.getKind() == InitializationKind::IK_Direct ||
2918 (Kind.getKind() == InitializationKind::IK_Copy &&
2919 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2920 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002921 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2922 Entity.getType().getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002923 // - Otherwise (i.e., for the remaining copy-initialization cases),
2924 // user-defined conversion sequences that can convert from the source
2925 // type to the destination type or (when a conversion function is
2926 // used) to a derived class thereof are enumerated as described in
2927 // 13.3.1.4, and the best one is chosen through overload resolution
2928 // (13.3).
2929 else
2930 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2931 return;
2932 }
2933
Douglas Gregor99a2e602009-12-16 01:38:02 +00002934 if (NumArgs > 1) {
2935 SetFailed(FK_TooManyInitsForScalar);
2936 return;
2937 }
2938 assert(NumArgs == 1 && "Zero-argument case handled above");
2939
Douglas Gregor20093b42009-12-09 23:02:17 +00002940 // - Otherwise, if the source type is a (possibly cv-qualified) class
2941 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002942 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002943 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2944 return;
2945 }
2946
2947 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002948 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002949 // conversions (Clause 4) will be used, if necessary, to convert the
2950 // initializer expression to the cv-unqualified version of the
2951 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002952 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002953 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2954}
2955
2956InitializationSequence::~InitializationSequence() {
2957 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2958 StepEnd = Steps.end();
2959 Step != StepEnd; ++Step)
2960 Step->Destroy();
2961}
2962
2963//===----------------------------------------------------------------------===//
2964// Perform initialization
2965//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002966static Sema::AssignmentAction
2967getAssignmentAction(const InitializedEntity &Entity) {
2968 switch(Entity.getKind()) {
2969 case InitializedEntity::EK_Variable:
2970 case InitializedEntity::EK_New:
2971 return Sema::AA_Initializing;
2972
2973 case InitializedEntity::EK_Parameter:
2974 // FIXME: Can we tell when we're sending vs. passing?
2975 return Sema::AA_Passing;
2976
2977 case InitializedEntity::EK_Result:
2978 return Sema::AA_Returning;
2979
2980 case InitializedEntity::EK_Exception:
2981 case InitializedEntity::EK_Base:
2982 llvm_unreachable("No assignment action for C++-specific initialization");
2983 break;
2984
2985 case InitializedEntity::EK_Temporary:
2986 // FIXME: Can we tell apart casting vs. converting?
2987 return Sema::AA_Casting;
2988
2989 case InitializedEntity::EK_Member:
2990 case InitializedEntity::EK_ArrayOrVectorElement:
2991 return Sema::AA_Initializing;
2992 }
2993
2994 return Sema::AA_Converting;
2995}
2996
2997static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2998 bool IsCopy) {
2999 switch (Entity.getKind()) {
3000 case InitializedEntity::EK_Result:
3001 case InitializedEntity::EK_Exception:
3002 return !IsCopy;
3003
3004 case InitializedEntity::EK_New:
3005 case InitializedEntity::EK_Variable:
3006 case InitializedEntity::EK_Base:
3007 case InitializedEntity::EK_Member:
3008 case InitializedEntity::EK_ArrayOrVectorElement:
3009 return false;
3010
3011 case InitializedEntity::EK_Parameter:
3012 case InitializedEntity::EK_Temporary:
3013 return true;
3014 }
3015
3016 llvm_unreachable("missed an InitializedEntity kind?");
3017}
3018
3019/// \brief If we need to perform an additional copy of the initialized object
3020/// for this kind of entity (e.g., the result of a function or an object being
3021/// thrown), make the copy.
3022static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3023 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003024 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003025 Sema::OwningExprResult CurInit) {
3026 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003027
3028 switch (Entity.getKind()) {
3029 case InitializedEntity::EK_Result:
3030 if (Entity.getType().getType()->isReferenceType())
3031 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003032 Loc = Entity.getReturnLoc();
3033 break;
3034
3035 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003036 Loc = Entity.getThrowLoc();
3037 break;
3038
3039 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003040 if (Entity.getType().getType()->isReferenceType() ||
3041 Kind.getKind() != InitializationKind::IK_Copy)
3042 return move(CurInit);
3043 Loc = Entity.getDecl()->getLocation();
3044 break;
3045
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003046 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003047 // FIXME: Do we need this initialization for a parameter?
3048 return move(CurInit);
3049
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003050 case InitializedEntity::EK_New:
3051 case InitializedEntity::EK_Temporary:
3052 case InitializedEntity::EK_Base:
3053 case InitializedEntity::EK_Member:
3054 case InitializedEntity::EK_ArrayOrVectorElement:
3055 // We don't need to copy for any of these initialized entities.
3056 return move(CurInit);
3057 }
3058
3059 Expr *CurInitExpr = (Expr *)CurInit.get();
3060 CXXRecordDecl *Class = 0;
3061 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3062 Class = cast<CXXRecordDecl>(Record->getDecl());
3063 if (!Class)
3064 return move(CurInit);
3065
3066 // Perform overload resolution using the class's copy constructors.
3067 DeclarationName ConstructorName
3068 = S.Context.DeclarationNames.getCXXConstructorName(
3069 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3070 DeclContext::lookup_iterator Con, ConEnd;
3071 OverloadCandidateSet CandidateSet;
3072 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3073 Con != ConEnd; ++Con) {
3074 // Find the constructor (which may be a template).
3075 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3076 if (!Constructor || Constructor->isInvalidDecl() ||
3077 !Constructor->isCopyConstructor(S.Context))
3078 continue;
3079
3080 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3081 }
3082
3083 OverloadCandidateSet::iterator Best;
3084 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3085 case OR_Success:
3086 break;
3087
3088 case OR_No_Viable_Function:
3089 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003090 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003091 << CurInitExpr->getSourceRange();
3092 S.PrintOverloadCandidates(CandidateSet, false);
3093 return S.ExprError();
3094
3095 case OR_Ambiguous:
3096 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003097 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003098 << CurInitExpr->getSourceRange();
3099 S.PrintOverloadCandidates(CandidateSet, true);
3100 return S.ExprError();
3101
3102 case OR_Deleted:
3103 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003104 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003105 << CurInitExpr->getSourceRange();
3106 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3107 << Best->Function->isDeleted();
3108 return S.ExprError();
3109 }
3110
3111 CurInit.release();
3112 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3113 cast<CXXConstructorDecl>(Best->Function),
3114 /*Elidable=*/true,
3115 Sema::MultiExprArg(S,
3116 (void**)&CurInitExpr, 1));
3117}
Douglas Gregor20093b42009-12-09 23:02:17 +00003118
3119Action::OwningExprResult
3120InitializationSequence::Perform(Sema &S,
3121 const InitializedEntity &Entity,
3122 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003123 Action::MultiExprArg Args,
3124 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003125 if (SequenceKind == FailedSequence) {
3126 unsigned NumArgs = Args.size();
3127 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3128 return S.ExprError();
3129 }
3130
3131 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003132 // If the declaration is a non-dependent, incomplete array type
3133 // that has an initializer, then its type will be completed once
3134 // the initializer is instantiated.
3135 if (ResultType && !Entity.getType().getType()->isDependentType() &&
3136 Args.size() == 1) {
3137 QualType DeclType = Entity.getType().getType();
3138 if (const IncompleteArrayType *ArrayT
3139 = S.Context.getAsIncompleteArrayType(DeclType)) {
3140 // FIXME: We don't currently have the ability to accurately
3141 // compute the length of an initializer list without
3142 // performing full type-checking of the initializer list
3143 // (since we have to determine where braces are implicitly
3144 // introduced and such). So, we fall back to making the array
3145 // type a dependently-sized array type with no specified
3146 // bound.
3147 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3148 SourceRange Brackets;
3149 // Scavange the location of the brackets from the entity, if we can.
3150 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
3151 IncompleteArrayTypeLoc ArrayLoc
3152 = cast<IncompleteArrayTypeLoc>(Entity.getType());
3153 Brackets = ArrayLoc.getBracketsRange();
3154 }
3155
3156 *ResultType
3157 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3158 /*NumElts=*/0,
3159 ArrayT->getSizeModifier(),
3160 ArrayT->getIndexTypeCVRQualifiers(),
3161 Brackets);
3162 }
3163
3164 }
3165 }
3166
Douglas Gregor20093b42009-12-09 23:02:17 +00003167 if (Kind.getKind() == InitializationKind::IK_Copy)
3168 return Sema::OwningExprResult(S, Args.release()[0]);
3169
3170 unsigned NumArgs = Args.size();
3171 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3172 SourceLocation(),
3173 (Expr **)Args.release(),
3174 NumArgs,
3175 SourceLocation()));
3176 }
3177
Douglas Gregor99a2e602009-12-16 01:38:02 +00003178 if (SequenceKind == NoInitialization)
3179 return S.Owned((Expr *)0);
3180
Douglas Gregor20093b42009-12-09 23:02:17 +00003181 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003182 if (ResultType)
3183 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003184
Douglas Gregor99a2e602009-12-16 01:38:02 +00003185 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3186
3187 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3188
3189 // For initialization steps that start with a single initializer,
3190 // grab the only argument out the Args and place it into the "current"
3191 // initializer.
3192 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003193 case SK_ResolveAddressOfOverloadedFunction:
3194 case SK_CastDerivedToBaseRValue:
3195 case SK_CastDerivedToBaseLValue:
3196 case SK_BindReference:
3197 case SK_BindReferenceToTemporary:
3198 case SK_UserConversion:
3199 case SK_QualificationConversionLValue:
3200 case SK_QualificationConversionRValue:
3201 case SK_ConversionSequence:
3202 case SK_ListInitialization:
3203 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003204 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003205 assert(Args.size() == 1);
3206 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3207 if (CurInit.isInvalid())
3208 return S.ExprError();
3209 break;
3210
3211 case SK_ConstructorInitialization:
3212 case SK_ZeroInitialization:
3213 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003214 }
3215
3216 // Walk through the computed steps for the initialization sequence,
3217 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003218 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003219 for (step_iterator Step = step_begin(), StepEnd = step_end();
3220 Step != StepEnd; ++Step) {
3221 if (CurInit.isInvalid())
3222 return S.ExprError();
3223
3224 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003225 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003226
3227 switch (Step->Kind) {
3228 case SK_ResolveAddressOfOverloadedFunction:
3229 // Overload resolution determined which function invoke; update the
3230 // initializer to reflect that choice.
3231 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3232 break;
3233
3234 case SK_CastDerivedToBaseRValue:
3235 case SK_CastDerivedToBaseLValue: {
3236 // We have a derived-to-base cast that produces either an rvalue or an
3237 // lvalue. Perform that cast.
3238
3239 // Casts to inaccessible base classes are allowed with C-style casts.
3240 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3241 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3242 CurInitExpr->getLocStart(),
3243 CurInitExpr->getSourceRange(),
3244 IgnoreBaseAccess))
3245 return S.ExprError();
3246
3247 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3248 CastExpr::CK_DerivedToBase,
3249 (Expr*)CurInit.release(),
3250 Step->Kind == SK_CastDerivedToBaseLValue));
3251 break;
3252 }
3253
3254 case SK_BindReference:
3255 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3256 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3257 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3258 << Entity.getType().getType().isVolatileQualified()
3259 << BitField->getDeclName()
3260 << CurInitExpr->getSourceRange();
3261 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3262 return S.ExprError();
3263 }
3264
3265 // Reference binding does not have any corresponding ASTs.
3266
3267 // Check exception specifications
3268 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3269 return S.ExprError();
3270 break;
3271
3272 case SK_BindReferenceToTemporary:
3273 // Check exception specifications
3274 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3275 return S.ExprError();
3276
3277 // FIXME: At present, we have no AST to describe when we need to make a
3278 // temporary to bind a reference to. We should.
3279 break;
3280
3281 case SK_UserConversion: {
3282 // We have a user-defined conversion that invokes either a constructor
3283 // or a conversion function.
3284 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003285 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003286 if (CXXConstructorDecl *Constructor
3287 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3288 // Build a call to the selected constructor.
3289 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3290 SourceLocation Loc = CurInitExpr->getLocStart();
3291 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3292
3293 // Determine the arguments required to actually perform the constructor
3294 // call.
3295 if (S.CompleteConstructorCall(Constructor,
3296 Sema::MultiExprArg(S,
3297 (void **)&CurInitExpr,
3298 1),
3299 Loc, ConstructorArgs))
3300 return S.ExprError();
3301
3302 // Build the an expression that constructs a temporary.
3303 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3304 move_arg(ConstructorArgs));
3305 if (CurInit.isInvalid())
3306 return S.ExprError();
3307
3308 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003309 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3310 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3311 S.IsDerivedFrom(SourceType, Class))
3312 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003313 } else {
3314 // Build a call to the conversion function.
3315 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003316
Douglas Gregor20093b42009-12-09 23:02:17 +00003317 // FIXME: Should we move this initialization into a separate
3318 // derived-to-base conversion? I believe the answer is "no", because
3319 // we don't want to turn off access control here for c-style casts.
3320 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3321 return S.ExprError();
3322
3323 // Do a little dance to make sure that CurInit has the proper
3324 // pointer.
3325 CurInit.release();
3326
3327 // Build the actual call to the conversion function.
3328 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3329 if (CurInit.isInvalid() || !CurInit.get())
3330 return S.ExprError();
3331
3332 CastKind = CastExpr::CK_UserDefinedConversion;
3333 }
3334
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003335 if (shouldBindAsTemporary(Entity, IsCopy))
3336 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3337
Douglas Gregor20093b42009-12-09 23:02:17 +00003338 CurInitExpr = CurInit.takeAs<Expr>();
3339 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3340 CastKind,
3341 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003342 false));
3343
3344 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003345 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 break;
3347 }
3348
3349 case SK_QualificationConversionLValue:
3350 case SK_QualificationConversionRValue:
3351 // Perform a qualification conversion; these can never go wrong.
3352 S.ImpCastExprToType(CurInitExpr, Step->Type,
3353 CastExpr::CK_NoOp,
3354 Step->Kind == SK_QualificationConversionLValue);
3355 CurInit.release();
3356 CurInit = S.Owned(CurInitExpr);
3357 break;
3358
3359 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003360 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003361 false, false, *Step->ICS))
3362 return S.ExprError();
3363
3364 CurInit.release();
3365 CurInit = S.Owned(CurInitExpr);
3366 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003367
3368 case SK_ListInitialization: {
3369 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3370 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003371 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003372 return S.ExprError();
3373
3374 CurInit.release();
3375 CurInit = S.Owned(InitList);
3376 break;
3377 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003378
3379 case SK_ConstructorInitialization: {
3380 CXXConstructorDecl *Constructor
3381 = cast<CXXConstructorDecl>(Step->Function);
3382
3383 // Build a call to the selected constructor.
3384 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3385 SourceLocation Loc = Kind.getLocation();
3386
3387 // Determine the arguments required to actually perform the constructor
3388 // call.
3389 if (S.CompleteConstructorCall(Constructor, move(Args),
3390 Loc, ConstructorArgs))
3391 return S.ExprError();
3392
3393 // Build the an expression that constructs a temporary.
Douglas Gregor745880f2009-12-20 22:01:25 +00003394 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType().getType(),
3395 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003396 move_arg(ConstructorArgs),
3397 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003398 if (CurInit.isInvalid())
3399 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003400
3401 bool Elidable
3402 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3403 if (shouldBindAsTemporary(Entity, Elidable))
3404 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3405
3406 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003407 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003408 break;
3409 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003410
3411 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003412 step_iterator NextStep = Step;
3413 ++NextStep;
3414 if (NextStep != StepEnd &&
3415 NextStep->Kind == SK_ConstructorInitialization) {
3416 // The need for zero-initialization is recorded directly into
3417 // the call to the object's constructor within the next step.
3418 ConstructorInitRequiresZeroInit = true;
3419 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3420 S.getLangOptions().CPlusPlus &&
3421 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003422 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3423 Kind.getRange().getBegin(),
3424 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003425 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003426 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003427 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003428 break;
3429 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003430
3431 case SK_CAssignment: {
3432 QualType SourceType = CurInitExpr->getType();
3433 Sema::AssignConvertType ConvTy =
3434 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
3435 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3436 Step->Type, SourceType,
3437 CurInitExpr, getAssignmentAction(Entity)))
3438 return S.ExprError();
3439
3440 CurInit.release();
3441 CurInit = S.Owned(CurInitExpr);
3442 break;
3443 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003444
3445 case SK_StringInit: {
3446 QualType Ty = Step->Type;
3447 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3448 break;
3449 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003450 }
3451 }
3452
3453 return move(CurInit);
3454}
3455
3456//===----------------------------------------------------------------------===//
3457// Diagnose initialization failures
3458//===----------------------------------------------------------------------===//
3459bool InitializationSequence::Diagnose(Sema &S,
3460 const InitializedEntity &Entity,
3461 const InitializationKind &Kind,
3462 Expr **Args, unsigned NumArgs) {
3463 if (SequenceKind != FailedSequence)
3464 return false;
3465
3466 QualType DestType = Entity.getType().getType();
3467 switch (Failure) {
3468 case FK_TooManyInitsForReference:
3469 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3470 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3471 break;
3472
3473 case FK_ArrayNeedsInitList:
3474 case FK_ArrayNeedsInitListOrStringLiteral:
3475 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3476 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3477 break;
3478
3479 case FK_AddressOfOverloadFailed:
3480 S.ResolveAddressOfOverloadedFunction(Args[0],
3481 DestType.getNonReferenceType(),
3482 true);
3483 break;
3484
3485 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003486 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003487 switch (FailedOverloadResult) {
3488 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003489 if (Failure == FK_UserConversionOverloadFailed)
3490 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3491 << Args[0]->getType() << DestType
3492 << Args[0]->getSourceRange();
3493 else
3494 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3495 << DestType << Args[0]->getType()
3496 << Args[0]->getSourceRange();
3497
Douglas Gregor20093b42009-12-09 23:02:17 +00003498 S.PrintOverloadCandidates(FailedCandidateSet, true);
3499 break;
3500
3501 case OR_No_Viable_Function:
3502 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3503 << Args[0]->getType() << DestType.getNonReferenceType()
3504 << Args[0]->getSourceRange();
3505 S.PrintOverloadCandidates(FailedCandidateSet, false);
3506 break;
3507
3508 case OR_Deleted: {
3509 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3510 << Args[0]->getType() << DestType.getNonReferenceType()
3511 << Args[0]->getSourceRange();
3512 OverloadCandidateSet::iterator Best;
3513 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3514 Kind.getLocation(),
3515 Best);
3516 if (Ovl == OR_Deleted) {
3517 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3518 << Best->Function->isDeleted();
3519 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003520 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003521 }
3522 break;
3523 }
3524
3525 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003526 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003527 break;
3528 }
3529 break;
3530
3531 case FK_NonConstLValueReferenceBindingToTemporary:
3532 case FK_NonConstLValueReferenceBindingToUnrelated:
3533 S.Diag(Kind.getLocation(),
3534 Failure == FK_NonConstLValueReferenceBindingToTemporary
3535 ? diag::err_lvalue_reference_bind_to_temporary
3536 : diag::err_lvalue_reference_bind_to_unrelated)
3537 << DestType.getNonReferenceType()
3538 << Args[0]->getType()
3539 << Args[0]->getSourceRange();
3540 break;
3541
3542 case FK_RValueReferenceBindingToLValue:
3543 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3544 << Args[0]->getSourceRange();
3545 break;
3546
3547 case FK_ReferenceInitDropsQualifiers:
3548 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3549 << DestType.getNonReferenceType()
3550 << Args[0]->getType()
3551 << Args[0]->getSourceRange();
3552 break;
3553
3554 case FK_ReferenceInitFailed:
3555 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3556 << DestType.getNonReferenceType()
3557 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3558 << Args[0]->getType()
3559 << Args[0]->getSourceRange();
3560 break;
3561
3562 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003563 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3564 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 << DestType
3566 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3567 << Args[0]->getType()
3568 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003569 break;
3570
3571 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003572 SourceRange R;
3573
3574 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3575 R = SourceRange(InitList->getInit(1)->getLocStart(),
3576 InitList->getLocEnd());
3577 else
3578 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003579
3580 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003581 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003582 break;
3583 }
3584
3585 case FK_ReferenceBindingToInitList:
3586 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3587 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3588 break;
3589
3590 case FK_InitListBadDestinationType:
3591 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3592 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3593 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003594
3595 case FK_ConstructorOverloadFailed: {
3596 SourceRange ArgsRange;
3597 if (NumArgs)
3598 ArgsRange = SourceRange(Args[0]->getLocStart(),
3599 Args[NumArgs - 1]->getLocEnd());
3600
3601 // FIXME: Using "DestType" for the entity we're printing is probably
3602 // bad.
3603 switch (FailedOverloadResult) {
3604 case OR_Ambiguous:
3605 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3606 << DestType << ArgsRange;
3607 S.PrintOverloadCandidates(FailedCandidateSet, true);
3608 break;
3609
3610 case OR_No_Viable_Function:
3611 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3612 << DestType << ArgsRange;
3613 S.PrintOverloadCandidates(FailedCandidateSet, false);
3614 break;
3615
3616 case OR_Deleted: {
3617 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3618 << true << DestType << ArgsRange;
3619 OverloadCandidateSet::iterator Best;
3620 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3621 Kind.getLocation(),
3622 Best);
3623 if (Ovl == OR_Deleted) {
3624 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3625 << Best->Function->isDeleted();
3626 } else {
3627 llvm_unreachable("Inconsistent overload resolution?");
3628 }
3629 break;
3630 }
3631
3632 case OR_Success:
3633 llvm_unreachable("Conversion did not fail!");
3634 break;
3635 }
3636 break;
3637 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003638
3639 case FK_DefaultInitOfConst:
3640 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3641 << DestType;
3642 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003643 }
3644
3645 return true;
3646}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003647
3648//===----------------------------------------------------------------------===//
3649// Initialization helper functions
3650//===----------------------------------------------------------------------===//
3651Sema::OwningExprResult
3652Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3653 SourceLocation EqualLoc,
3654 OwningExprResult Init) {
3655 if (Init.isInvalid())
3656 return ExprError();
3657
3658 Expr *InitE = (Expr *)Init.get();
3659 assert(InitE && "No initialization expression?");
3660
3661 if (EqualLoc.isInvalid())
3662 EqualLoc = InitE->getLocStart();
3663
3664 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3665 EqualLoc);
3666 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3667 Init.release();
3668 return Seq.Perform(*this, Entity, Kind,
3669 MultiExprArg(*this, (void**)&InitE, 1));
3670}