blob: 28e11a1010fb8f2ce1e4bc45920ec86535ed97e7 [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.
195 if (DeclType->isReferenceType())
Douglas Gregor739d8282009-09-23 23:04:10 +0000196 return CheckReferenceInit(Init, DeclType, InitLoc,
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000197 /*SuppressUserConversions=*/false,
198 /*AllowExplicit=*/DirectInit,
199 /*ForceRValue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000201 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
202 // of unknown size ("[]") or an object type that is not a variable array type.
203 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
204 return Diag(InitLoc, diag::err_variable_object_no_init)
205 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000207 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
208 if (!InitList) {
209 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000210 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
211 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000212 return false;
213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000215 // C++ [dcl.init]p14:
216 // -- If the destination type is a (possibly cv-qualified) class
217 // type:
218 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
219 QualType DeclTypeC = Context.getCanonicalType(DeclType);
220 QualType InitTypeC = Context.getCanonicalType(Init->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000222 // -- If the initialization is direct-initialization, or if it is
223 // copy-initialization where the cv-unqualified version of the
224 // source type is the same class as, or a derived class of, the
225 // class of the destination, constructors are considered.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000226 if ((DeclTypeC.getLocalUnqualifiedType()
227 == InitTypeC.getLocalUnqualifiedType()) ||
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000228 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000229 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000230 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000232 // No need to make a CXXConstructExpr if both the ctor and dtor are
233 // trivial.
234 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
235 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Douglas Gregor39da0b82009-09-09 23:08:42 +0000237 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
238
Douglas Gregor20093b42009-12-09 23:02:17 +0000239 // FIXME: Poor location information
240 InitializationKind InitKind
241 = InitializationKind::CreateCopy(Init->getLocStart(),
242 SourceLocation());
243 if (DirectInit)
244 InitKind = InitializationKind::CreateDirect(Init->getLocStart(),
245 SourceLocation(),
246 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000247 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000248 = PerformInitializationByConstructor(DeclType,
249 MultiExprArg(*this,
250 (void **)&Init, 1),
251 InitLoc, Init->getSourceRange(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000252 InitEntity, InitKind,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000253 ConstructorArgs);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000254 if (!Constructor)
255 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000256
257 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000258 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000259 DeclType, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000260 move_arg(ConstructorArgs));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000261 if (InitResult.isInvalid())
262 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000264 Init = InitResult.takeAs<Expr>();
Anders Carlsson2078bb92009-05-27 16:10:08 +0000265 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000266 }
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000268 // -- Otherwise (i.e., for the remaining copy-initialization
269 // cases), user-defined conversion sequences that can
270 // convert from the source type to the destination type or
271 // (when a conversion function is used) to a derived class
272 // thereof are enumerated as described in 13.3.1.4, and the
273 // best one is chosen through overload resolution
274 // (13.3). If the conversion cannot be done or is
275 // ambiguous, the initialization is ill-formed. The
276 // function selected is called with the initializer
277 // expression as its argument; if the function is a
278 // constructor, the call initializes a temporary of the
279 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000280 // FIXME: We're pretending to do copy elision here; return to this when we
281 // have ASTs for such things.
Douglas Gregor68647482009-12-16 03:45:30 +0000282 if (!PerformImplicitConversion(Init, DeclType, Sema::AA_Initializing))
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000283 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000285 if (InitEntity)
286 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000287 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
288 << Init->getType() << Init->getSourceRange();
289 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000290 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
291 << Init->getType() << Init->getSourceRange();
292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000294 // C99 6.7.8p16.
295 if (DeclType->isArrayType())
296 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000297 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattner95e8d652009-02-24 22:46:58 +0000299 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 }
301
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000302 bool hadError = CheckInitList(InitList, DeclType);
303 Init = InitList;
304 return hadError;
305}
306
307//===----------------------------------------------------------------------===//
308// Semantic checking for initializer lists.
309//===----------------------------------------------------------------------===//
310
Douglas Gregor9e80f722009-01-29 01:05:33 +0000311/// @brief Semantic checking for initializer lists.
312///
313/// The InitListChecker class contains a set of routines that each
314/// handle the initialization of a certain kind of entity, e.g.,
315/// arrays, vectors, struct/union types, scalars, etc. The
316/// InitListChecker itself performs a recursive walk of the subobject
317/// structure of the type to be initialized, while stepping through
318/// the initializer list one element at a time. The IList and Index
319/// parameters to each of the Check* routines contain the active
320/// (syntactic) initializer list and the index into that initializer
321/// list that represents the current initializer. Each routine is
322/// responsible for moving that Index forward as it consumes elements.
323///
324/// Each Check* routine also has a StructuredList/StructuredIndex
325/// arguments, which contains the current the "structured" (semantic)
326/// initializer list and the index into that initializer list where we
327/// are copying initializers as we map them over to the semantic
328/// list. Once we have completed our recursive walk of the subobject
329/// structure, we will have constructed a full semantic initializer
330/// list.
331///
332/// C99 designators cause changes in the initializer list traversal,
333/// because they make the initialization "jump" into a specific
334/// subobject and then continue the initialization from that
335/// point. CheckDesignatedInitializer() recursively steps into the
336/// designated subobject and manages backing out the recursion to
337/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000338namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000339class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000340 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000341 bool hadError;
342 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
343 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
345 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000346 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000347 unsigned &StructuredIndex,
348 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000349 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000350 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000351 unsigned &StructuredIndex,
352 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000353 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
354 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000355 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000356 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000357 unsigned &StructuredIndex,
358 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000359 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000360 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000361 InitListExpr *StructuredList,
362 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000363 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000364 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000365 InitListExpr *StructuredList,
366 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000368 unsigned &Index,
369 InitListExpr *StructuredList,
370 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000371 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000372 InitListExpr *StructuredList,
373 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000374 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
375 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000376 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000377 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000378 unsigned &StructuredIndex,
379 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
381 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000382 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000383 InitListExpr *StructuredList,
384 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000386 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000387 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000388 RecordDecl::field_iterator *NextField,
389 llvm::APSInt *NextElementIndex,
390 unsigned &Index,
391 InitListExpr *StructuredList,
392 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000393 bool FinishSubobjectInit,
394 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000395 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
396 QualType CurrentObjectType,
397 InitListExpr *StructuredList,
398 unsigned StructuredIndex,
399 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000400 void UpdateStructuredListElement(InitListExpr *StructuredList,
401 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000402 Expr *expr);
403 int numArrayElements(QualType DeclType);
404 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000405
406 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000407public:
Chris Lattner08202542009-02-24 22:50:46 +0000408 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000409 bool HadError() { return hadError; }
410
411 // @brief Retrieves the fully-structured initializer list used for
412 // semantic analysis and code generation.
413 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
414};
Chris Lattner8b419b92009-02-24 22:48:58 +0000415} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000416
Douglas Gregor4c678342009-01-28 21:54:33 +0000417/// Recursively replaces NULL values within the given initializer list
418/// with expressions that perform value-initialization of the
419/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000420void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000421 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000422 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000423 SourceLocation Loc = ILE->getSourceRange().getBegin();
424 if (ILE->getSyntacticForm())
425 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Ted Kremenek6217b802009-07-29 21:53:49 +0000427 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000428 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000429 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000430 Field = RType->getDecl()->field_begin(),
431 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000432 Field != FieldEnd; ++Field) {
433 if (Field->isUnnamedBitfield())
434 continue;
435
Douglas Gregor87fd7032009-02-02 17:43:21 +0000436 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000437 if (Field->getType()->isReferenceType()) {
438 // C++ [dcl.init.aggr]p9:
439 // If an incomplete or empty initializer-list leaves a
440 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000441 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000442 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000443 << Field->getType()
444 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000445 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000446 diag::note_uninit_reference_member);
447 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000448 return;
Chris Lattner08202542009-02-24 22:50:46 +0000449 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000450 hadError = true;
451 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000452 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000453
Mike Stump390b4cc2009-05-16 07:39:55 +0000454 // FIXME: If value-initialization involves calling a constructor, should
455 // we make that call explicit in the representation (even when it means
456 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000457 if (Init < NumInits && !hadError)
Mike Stump1eb44332009-09-09 15:08:12 +0000458 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000459 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000460 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000461 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000462 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000463 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000464
465 // Only look at the first initialization of a union.
466 if (RType->getDecl()->isUnion())
467 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 }
469
470 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000471 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000472
473 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Douglas Gregor87fd7032009-02-02 17:43:21 +0000475 unsigned NumInits = ILE->getNumInits();
476 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000477 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000479 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
480 NumElements = CAType->getSize().getZExtValue();
John McCall183700f2009-09-21 23:43:11 +0000481 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000482 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000483 NumElements = VType->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000484 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Douglas Gregor87fd7032009-02-02 17:43:21 +0000487 for (unsigned Init = 0; Init != NumElements; ++Init) {
488 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000489 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000490 hadError = true;
491 return;
492 }
493
Mike Stump390b4cc2009-05-16 07:39:55 +0000494 // FIXME: If value-initialization involves calling a constructor, should
495 // we make that call explicit in the representation (even when it means
496 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000497 if (Init < NumInits && !hadError)
Mike Stump1eb44332009-09-09 15:08:12 +0000498 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000499 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000500 } else if (InitListExpr *InnerILE
501 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000502 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 }
504}
505
Chris Lattner68355a52009-01-29 05:10:57 +0000506
Chris Lattner08202542009-02-24 22:50:46 +0000507InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
508 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000509 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000510
Eli Friedmanb85f7072008-05-19 19:16:24 +0000511 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000512 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000513 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000514 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000515 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
516 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000517
Douglas Gregor930d8b52009-01-30 22:09:00 +0000518 if (!hadError)
519 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000520}
521
522int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000523 // FIXME: use a proper constant
524 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000525 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000526 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000527 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
528 }
529 return maxElements;
530}
531
532int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000533 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000534 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000535 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000536 Field = structDecl->field_begin(),
537 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000538 Field != FieldEnd; ++Field) {
539 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
540 ++InitializableMembers;
541 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000542 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000543 return std::min(InitializableMembers, 1);
544 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000545}
546
Mike Stump1eb44332009-09-09 15:08:12 +0000547void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000548 QualType T, unsigned &Index,
549 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000550 unsigned &StructuredIndex,
551 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000552 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Steve Naroff0cca7492008-05-01 22:18:59 +0000554 if (T->isArrayType())
555 maxElements = numArrayElements(T);
556 else if (T->isStructureType() || T->isUnionType())
557 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000558 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000559 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000560 else
561 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000562
Eli Friedman402256f2008-05-25 13:49:22 +0000563 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000564 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000565 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000566 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000567 hadError = true;
568 return;
569 }
570
Douglas Gregor4c678342009-01-28 21:54:33 +0000571 // Build a structured initializer list corresponding to this subobject.
572 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000573 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
574 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000575 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
576 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000577 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000578
Douglas Gregor4c678342009-01-28 21:54:33 +0000579 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000580 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000581 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000582 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000583 StructuredSubobjectInitIndex,
584 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000585 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000586 StructuredSubobjectInitList->setType(T);
587
Douglas Gregored8a93d2009-03-01 17:12:46 +0000588 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000589 // range corresponds with the end of the last initializer it used.
590 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000591 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000592 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
593 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
594 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000595}
596
Steve Naroffa647caa2008-05-06 00:23:44 +0000597void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000598 unsigned &Index,
599 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000600 unsigned &StructuredIndex,
601 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000602 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 SyntacticToSemantic[IList] = StructuredList;
604 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000605 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000606 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000607 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000609 if (hadError)
610 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000611
Eli Friedman638e1442008-05-25 13:22:35 +0000612 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000613 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000614 if (StructuredIndex == 1 &&
615 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000616 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000617 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000618 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000619 hadError = true;
620 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000621 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000623 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000624 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000625 // Don't complain for incomplete types, since we'll get an error
626 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000627 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000628 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000629 CurrentObjectType->isArrayType()? 0 :
630 CurrentObjectType->isVectorType()? 1 :
631 CurrentObjectType->isScalarType()? 2 :
632 CurrentObjectType->isUnionType()? 3 :
633 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000634
635 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000636 if (SemaRef.getLangOptions().CPlusPlus) {
637 DK = diag::err_excess_initializers;
638 hadError = true;
639 }
Nate Begeman08634522009-07-07 21:53:06 +0000640 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
641 DK = diag::err_excess_initializers;
642 hadError = true;
643 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000644
Chris Lattner08202542009-02-24 22:50:46 +0000645 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000646 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000647 }
648 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000649
Eli Friedman759f2522009-05-16 11:45:48 +0000650 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000651 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000652 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000653 << CodeModificationHint::CreateRemoval(IList->getLocStart())
654 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000655}
656
Eli Friedmanb85f7072008-05-19 19:16:24 +0000657void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000658 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000659 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000660 unsigned &Index,
661 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000662 unsigned &StructuredIndex,
663 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000664 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000665 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000666 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000667 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000668 } else if (DeclType->isAggregateType()) {
669 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000670 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000671 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000673 StructuredList, StructuredIndex,
674 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000675 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000676 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000677 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000678 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000679 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
680 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000681 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000683 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
684 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000686 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000687 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000688 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000689 } else if (DeclType->isRecordType()) {
690 // C++ [dcl.init]p14:
691 // [...] If the class is an aggregate (8.5.1), and the initializer
692 // is a brace-enclosed list, see 8.5.1.
693 //
694 // Note: 8.5.1 is handled below; here, we diagnose the case where
695 // we have an initializer list and a destination type that is not
696 // an aggregate.
697 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000698 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000699 << DeclType << IList->getSourceRange();
700 hadError = true;
701 } else if (DeclType->isReferenceType()) {
702 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000703 } else {
704 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000705 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000706 assert(0 && "Unsupported initializer type");
707 }
708}
709
Eli Friedmanb85f7072008-05-19 19:16:24 +0000710void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000711 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000712 unsigned &Index,
713 InitListExpr *StructuredList,
714 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000715 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000716 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
717 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000718 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000719 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000720 = getStructuredSubobjectInit(IList, Index, ElemType,
721 StructuredList, StructuredIndex,
722 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000723 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000724 newStructuredList, newStructuredIndex);
725 ++StructuredIndex;
726 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000727 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
728 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000729 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000730 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000731 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000732 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000733 } else if (ElemType->isReferenceType()) {
734 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000735 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000736 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000737 // C++ [dcl.init.aggr]p12:
738 // All implicit type conversions (clause 4) are considered when
739 // initializing the aggregate member with an ini- tializer from
740 // an initializer-list. If the initializer can initialize a
741 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000742 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000743 = SemaRef.TryCopyInitialization(expr, ElemType,
744 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000745 /*ForceRValue=*/false,
746 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000747
Douglas Gregor930d8b52009-01-30 22:09:00 +0000748 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000749 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000750 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000751 hadError = true;
752 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
753 ++Index;
754 return;
755 }
756
757 // Fall through for subaggregate initialization
758 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000759 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000760 //
761 // The initializer for a structure or union object that has
762 // automatic storage duration shall be either an initializer
763 // list as described below, or a single expression that has
764 // compatible structure or union type. In the latter case, the
765 // initial value of the object, including unnamed members, is
766 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000767 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000768 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000769 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
770 ++Index;
771 return;
772 }
773
774 // Fall through for subaggregate initialization
775 }
776
777 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000778 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000779 // [...] Otherwise, if the member is itself a non-empty
780 // subaggregate, brace elision is assumed and the initializer is
781 // considered for the initialization of the first member of
782 // the subaggregate.
783 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000784 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000785 StructuredIndex);
786 ++StructuredIndex;
787 } else {
788 // We cannot initialize this element, so let
789 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000790 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000791 hadError = true;
792 ++Index;
793 ++StructuredIndex;
794 }
795 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000796}
797
Douglas Gregor930d8b52009-01-30 22:09:00 +0000798void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000799 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000800 InitListExpr *StructuredList,
801 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000802 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000803 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000804 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000805 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000806 diag::err_many_braces_around_scalar_init)
807 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000808 hadError = true;
809 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000810 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000811 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000812 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000813 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000814 diag::err_designator_for_scalar_init)
815 << DeclType << expr->getSourceRange();
816 hadError = true;
817 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000818 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000819 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000820 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000821
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000822 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000823 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000824 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000825 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000826 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000827 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000828 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000829 if (hadError)
830 ++StructuredIndex;
831 else
832 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000833 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000834 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000835 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000836 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000837 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000838 ++Index;
839 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000840 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000841 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000842}
843
Douglas Gregor930d8b52009-01-30 22:09:00 +0000844void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
845 unsigned &Index,
846 InitListExpr *StructuredList,
847 unsigned &StructuredIndex) {
848 if (Index < IList->getNumInits()) {
849 Expr *expr = IList->getInit(Index);
850 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000851 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000852 << DeclType << IList->getSourceRange();
853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
856 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000857 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000858
859 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000860 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000861 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000862 /*SuppressUserConversions=*/false,
863 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000864 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000865 hadError = true;
866 else if (savExpr != expr) {
867 // The type was promoted, update initializer list.
868 IList->setInit(Index, expr);
869 }
870 if (hadError)
871 ++StructuredIndex;
872 else
873 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
874 ++Index;
875 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000876 // FIXME: It would be wonderful if we could point at the actual member. In
877 // general, it would be useful to pass location information down the stack,
878 // so that we know the location (or decl) of the "current object" being
879 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000880 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000881 diag::err_init_reference_member_uninitialized)
882 << DeclType
883 << IList->getSourceRange();
884 hadError = true;
885 ++Index;
886 ++StructuredIndex;
887 return;
888 }
889}
890
Mike Stump1eb44332009-09-09 15:08:12 +0000891void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000892 unsigned &Index,
893 InitListExpr *StructuredList,
894 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000895 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000896 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000897 unsigned maxElements = VT->getNumElements();
898 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000899 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Nate Begeman2ef13e52009-08-10 23:49:36 +0000901 if (!SemaRef.getLangOptions().OpenCL) {
902 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
903 // Don't attempt to go past the end of the init list
904 if (Index >= IList->getNumInits())
905 break;
906 CheckSubElementType(IList, elementType, Index,
907 StructuredList, StructuredIndex);
908 }
909 } else {
910 // OpenCL initializers allows vectors to be constructed from vectors.
911 for (unsigned i = 0; i < maxElements; ++i) {
912 // Don't attempt to go past the end of the init list
913 if (Index >= IList->getNumInits())
914 break;
915 QualType IType = IList->getInit(Index)->getType();
916 if (!IType->isVectorType()) {
917 CheckSubElementType(IList, elementType, Index,
918 StructuredList, StructuredIndex);
919 ++numEltsInit;
920 } else {
John McCall183700f2009-09-21 23:43:11 +0000921 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000922 unsigned numIElts = IVT->getNumElements();
923 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
924 numIElts);
925 CheckSubElementType(IList, VecType, Index,
926 StructuredList, StructuredIndex);
927 numEltsInit += numIElts;
928 }
929 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000930 }
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Nate Begeman2ef13e52009-08-10 23:49:36 +0000932 // OpenCL & AltiVec require all elements to be initialized.
933 if (numEltsInit != maxElements)
934 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
935 SemaRef.Diag(IList->getSourceRange().getBegin(),
936 diag::err_vector_incorrect_num_initializers)
937 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000938 }
939}
940
Mike Stump1eb44332009-09-09 15:08:12 +0000941void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000942 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000943 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000944 unsigned &Index,
945 InitListExpr *StructuredList,
946 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000947 // Check for the special-case of initializing an array with a string.
948 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000949 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
950 SemaRef.Context)) {
951 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000952 // We place the string literal directly into the resulting
953 // initializer list. This is the only place where the structure
954 // of the structured initializer list doesn't match exactly,
955 // because doing so would involve allocating one character
956 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000957 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000958 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000959 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000960 return;
961 }
962 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000963 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000964 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000965 // Check for VLAs; in standard C it would be possible to check this
966 // earlier, but I don't know where clang accepts VLAs (gcc accepts
967 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000968 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000969 diag::err_variable_object_no_init)
970 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000971 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000972 ++Index;
973 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000974 return;
975 }
976
Douglas Gregor05c13a32009-01-22 00:58:24 +0000977 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000978 llvm::APSInt maxElements(elementIndex.getBitWidth(),
979 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000980 bool maxElementsKnown = false;
981 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000982 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000983 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000984 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000985 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986 maxElementsKnown = true;
987 }
988
Chris Lattner08202542009-02-24 22:50:46 +0000989 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000990 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000991 while (Index < IList->getNumInits()) {
992 Expr *Init = IList->getInit(Index);
993 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000994 // If we're not the subobject that matches up with the '{' for
995 // the designator, we shouldn't be handling the
996 // designator. Return immediately.
997 if (!SubobjectIsDesignatorContext)
998 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000999
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001000 // Handle this designated initializer. elementIndex will be
1001 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +00001002 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001003 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001004 StructuredList, StructuredIndex, true,
1005 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001006 hadError = true;
1007 continue;
1008 }
1009
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001010 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1011 maxElements.extend(elementIndex.getBitWidth());
1012 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1013 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001014 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001015
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001016 // If the array is of incomplete type, keep track of the number of
1017 // elements in the initializer.
1018 if (!maxElementsKnown && elementIndex > maxElements)
1019 maxElements = elementIndex;
1020
Douglas Gregor05c13a32009-01-22 00:58:24 +00001021 continue;
1022 }
1023
1024 // If we know the maximum number of elements, and we've already
1025 // hit it, stop consuming elements in the initializer list.
1026 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001027 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001028
1029 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001030 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001031 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001032 ++elementIndex;
1033
1034 // If the array is of incomplete type, keep track of the number of
1035 // elements in the initializer.
1036 if (!maxElementsKnown && elementIndex > maxElements)
1037 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001038 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001039 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001040 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001041 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001042 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001043 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001044 // Sizing an array implicitly to zero is not allowed by ISO C,
1045 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001046 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001047 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001048 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001049
Mike Stump1eb44332009-09-09 15:08:12 +00001050 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001051 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001052 }
1053}
1054
Mike Stump1eb44332009-09-09 15:08:12 +00001055void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1056 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001057 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001058 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001059 unsigned &Index,
1060 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001061 unsigned &StructuredIndex,
1062 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001063 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Eli Friedmanb85f7072008-05-19 19:16:24 +00001065 // If the record is invalid, some of it's members are invalid. To avoid
1066 // confusion, we forgo checking the intializer for the entire record.
1067 if (structDecl->isInvalidDecl()) {
1068 hadError = true;
1069 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001070 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001071
1072 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1073 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001074 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001075 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001076 Field != FieldEnd; ++Field) {
1077 if (Field->getDeclName()) {
1078 StructuredList->setInitializedFieldInUnion(*Field);
1079 break;
1080 }
1081 }
1082 return;
1083 }
1084
Douglas Gregor05c13a32009-01-22 00:58:24 +00001085 // If structDecl is a forward declaration, this loop won't do
1086 // anything except look at designated initializers; That's okay,
1087 // because an error should get printed out elsewhere. It might be
1088 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001089 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001090 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001091 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001092 while (Index < IList->getNumInits()) {
1093 Expr *Init = IList->getInit(Index);
1094
1095 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001096 // If we're not the subobject that matches up with the '{' for
1097 // the designator, we shouldn't be handling the
1098 // designator. Return immediately.
1099 if (!SubobjectIsDesignatorContext)
1100 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001101
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001102 // Handle this designated initializer. Field will be updated to
1103 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001104 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001105 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001106 StructuredList, StructuredIndex,
1107 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001108 hadError = true;
1109
Douglas Gregordfb5e592009-02-12 19:00:39 +00001110 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001111 continue;
1112 }
1113
1114 if (Field == FieldEnd) {
1115 // We've run out of fields. We're done.
1116 break;
1117 }
1118
Douglas Gregordfb5e592009-02-12 19:00:39 +00001119 // We've already initialized a member of a union. We're done.
1120 if (InitializedSomething && DeclType->isUnionType())
1121 break;
1122
Douglas Gregor44b43212008-12-11 16:49:14 +00001123 // If we've hit the flexible array member at the end, we're done.
1124 if (Field->getType()->isIncompleteArrayType())
1125 break;
1126
Douglas Gregor0bb76892009-01-29 16:53:55 +00001127 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001128 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001129 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001130 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001131 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001132
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001133 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001134 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001135 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001136
1137 if (DeclType->isUnionType()) {
1138 // Initialize the first field within the union.
1139 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001140 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001141
1142 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001143 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001144
Mike Stump1eb44332009-09-09 15:08:12 +00001145 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001146 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001147 return;
1148
1149 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001150 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001151 (!isa<InitListExpr>(IList->getInit(Index)) ||
1152 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001153 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001154 diag::err_flexible_array_init_nonempty)
1155 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001156 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001157 << *Field;
1158 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001159 ++Index;
1160 return;
1161 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001162 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001163 diag::ext_flexible_array_init)
1164 << IList->getInit(Index)->getSourceRange().getBegin();
1165 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1166 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001167 }
1168
Douglas Gregora6457962009-03-20 00:32:56 +00001169 if (isa<InitListExpr>(IList->getInit(Index)))
1170 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1171 StructuredIndex);
1172 else
1173 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1174 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001175}
Steve Naroff0cca7492008-05-01 22:18:59 +00001176
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001177/// \brief Expand a field designator that refers to a member of an
1178/// anonymous struct or union into a series of field designators that
1179/// refers to the field within the appropriate subobject.
1180///
1181/// Field/FieldIndex will be updated to point to the (new)
1182/// currently-designated field.
1183static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001184 DesignatedInitExpr *DIE,
1185 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001186 FieldDecl *Field,
1187 RecordDecl::field_iterator &FieldIter,
1188 unsigned &FieldIndex) {
1189 typedef DesignatedInitExpr::Designator Designator;
1190
1191 // Build the path from the current object to the member of the
1192 // anonymous struct/union (backwards).
1193 llvm::SmallVector<FieldDecl *, 4> Path;
1194 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001196 // Build the replacement designators.
1197 llvm::SmallVector<Designator, 4> Replacements;
1198 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1199 FI = Path.rbegin(), FIEnd = Path.rend();
1200 FI != FIEnd; ++FI) {
1201 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001202 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001203 DIE->getDesignator(DesigIdx)->getDotLoc(),
1204 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1205 else
1206 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1207 SourceLocation()));
1208 Replacements.back().setField(*FI);
1209 }
1210
1211 // Expand the current designator into the set of replacement
1212 // designators, so we have a full subobject path down to where the
1213 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001214 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001215 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001217 // Update FieldIter/FieldIndex;
1218 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001219 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001220 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001221 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001222 FieldIter != FEnd; ++FieldIter) {
1223 if (FieldIter->isUnnamedBitfield())
1224 continue;
1225
1226 if (*FieldIter == Path.back())
1227 return;
1228
1229 ++FieldIndex;
1230 }
1231
1232 assert(false && "Unable to find anonymous struct/union field");
1233}
1234
Douglas Gregor05c13a32009-01-22 00:58:24 +00001235/// @brief Check the well-formedness of a C99 designated initializer.
1236///
1237/// Determines whether the designated initializer @p DIE, which
1238/// resides at the given @p Index within the initializer list @p
1239/// IList, is well-formed for a current object of type @p DeclType
1240/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001241/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001242/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001243///
1244/// @param IList The initializer list in which this designated
1245/// initializer occurs.
1246///
Douglas Gregor71199712009-04-15 04:56:10 +00001247/// @param DIE The designated initializer expression.
1248///
1249/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001250///
1251/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1252/// into which the designation in @p DIE should refer.
1253///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001254/// @param NextField If non-NULL and the first designator in @p DIE is
1255/// a field, this will be set to the field declaration corresponding
1256/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001257///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001258/// @param NextElementIndex If non-NULL and the first designator in @p
1259/// DIE is an array designator or GNU array-range designator, this
1260/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001261///
1262/// @param Index Index into @p IList where the designated initializer
1263/// @p DIE occurs.
1264///
Douglas Gregor4c678342009-01-28 21:54:33 +00001265/// @param StructuredList The initializer list expression that
1266/// describes all of the subobject initializers in the order they'll
1267/// actually be initialized.
1268///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001269/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001270bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001271InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001272 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001273 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001274 QualType &CurrentObjectType,
1275 RecordDecl::field_iterator *NextField,
1276 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001277 unsigned &Index,
1278 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001279 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001280 bool FinishSubobjectInit,
1281 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001282 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001283 // Check the actual initialization for the designated object type.
1284 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001285
1286 // Temporarily remove the designator expression from the
1287 // initializer list that the child calls see, so that we don't try
1288 // to re-process the designator.
1289 unsigned OldIndex = Index;
1290 IList->setInit(OldIndex, DIE->getInit());
1291
1292 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001293 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001294
1295 // Restore the designated initializer expression in the syntactic
1296 // form of the initializer list.
1297 if (IList->getInit(OldIndex) != DIE->getInit())
1298 DIE->setInit(IList->getInit(OldIndex));
1299 IList->setInit(OldIndex, DIE);
1300
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001301 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001302 }
1303
Douglas Gregor71199712009-04-15 04:56:10 +00001304 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001305 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001306 "Need a non-designated initializer list to start from");
1307
Douglas Gregor71199712009-04-15 04:56:10 +00001308 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001309 // Determine the structural initializer list that corresponds to the
1310 // current subobject.
1311 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001312 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001313 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001314 SourceRange(D->getStartLocation(),
1315 DIE->getSourceRange().getEnd()));
1316 assert(StructuredList && "Expected a structured initializer list");
1317
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001318 if (D->isFieldDesignator()) {
1319 // C99 6.7.8p7:
1320 //
1321 // If a designator has the form
1322 //
1323 // . identifier
1324 //
1325 // then the current object (defined below) shall have
1326 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001327 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001328 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001329 if (!RT) {
1330 SourceLocation Loc = D->getDotLoc();
1331 if (Loc.isInvalid())
1332 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001333 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1334 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001335 ++Index;
1336 return true;
1337 }
1338
Douglas Gregor4c678342009-01-28 21:54:33 +00001339 // Note: we perform a linear search of the fields here, despite
1340 // the fact that we have a faster lookup method, because we always
1341 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001342 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001344 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001345 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001346 Field = RT->getDecl()->field_begin(),
1347 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 for (; Field != FieldEnd; ++Field) {
1349 if (Field->isUnnamedBitfield())
1350 continue;
1351
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001352 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001353 break;
1354
1355 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001356 }
1357
Douglas Gregor4c678342009-01-28 21:54:33 +00001358 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001359 // There was no normal field in the struct with the designated
1360 // name. Perform another lookup for this name, which may find
1361 // something that we can't designate (e.g., a member function),
1362 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001363 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001364 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 if (Lookup.first == Lookup.second) {
1366 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001367 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001368 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001369 ++Index;
1370 return true;
1371 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1372 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1373 ->isAnonymousStructOrUnion()) {
1374 // Handle an field designator that refers to a member of an
1375 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001377 cast<FieldDecl>(*Lookup.first),
1378 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001379 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001380 } else {
1381 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001382 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001383 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001384 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001385 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001386 ++Index;
1387 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001388 }
1389 } else if (!KnownField &&
1390 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001391 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001392 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1393 Field, FieldIndex);
1394 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001395 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001396
1397 // All of the fields of a union are located at the same place in
1398 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001399 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001400 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001401 StructuredList->setInitializedFieldInUnion(*Field);
1402 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001403
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001404 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Douglas Gregor4c678342009-01-28 21:54:33 +00001407 // Make sure that our non-designated initializer list has space
1408 // for a subobject corresponding to this field.
1409 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001410 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001411
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001412 // This designator names a flexible array member.
1413 if (Field->getType()->isIncompleteArrayType()) {
1414 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001415 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001416 // We can't designate an object within the flexible array
1417 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001418 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001419 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001420 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001421 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001422 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001423 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001424 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001425 << *Field;
1426 Invalid = true;
1427 }
1428
1429 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1430 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001431 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001432 diag::err_flexible_array_init_needs_braces)
1433 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001434 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001435 << *Field;
1436 Invalid = true;
1437 }
1438
1439 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001440 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001441 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001442 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001443 diag::err_flexible_array_init_nonempty)
1444 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001445 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001446 << *Field;
1447 Invalid = true;
1448 }
1449
1450 if (Invalid) {
1451 ++Index;
1452 return true;
1453 }
1454
1455 // Initialize the array.
1456 bool prevHadError = hadError;
1457 unsigned newStructuredIndex = FieldIndex;
1458 unsigned OldIndex = Index;
1459 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001460 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001461 StructuredList, newStructuredIndex);
1462 IList->setInit(OldIndex, DIE);
1463 if (hadError && !prevHadError) {
1464 ++Field;
1465 ++FieldIndex;
1466 if (NextField)
1467 *NextField = Field;
1468 StructuredIndex = FieldIndex;
1469 return true;
1470 }
1471 } else {
1472 // Recurse to check later designated subobjects.
1473 QualType FieldType = (*Field)->getType();
1474 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001475 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1476 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001477 true, false))
1478 return true;
1479 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001480
1481 // Find the position of the next field to be initialized in this
1482 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001483 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001484 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001485
1486 // If this the first designator, our caller will continue checking
1487 // the rest of this struct/class/union subobject.
1488 if (IsFirstDesignator) {
1489 if (NextField)
1490 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001491 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001492 return false;
1493 }
1494
Douglas Gregor34e79462009-01-28 23:36:17 +00001495 if (!FinishSubobjectInit)
1496 return false;
1497
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001498 // We've already initialized something in the union; we're done.
1499 if (RT->getDecl()->isUnion())
1500 return hadError;
1501
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001502 // Check the remaining fields within this class/struct/union subobject.
1503 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001504 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1505 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001506 return hadError && !prevHadError;
1507 }
1508
1509 // C99 6.7.8p6:
1510 //
1511 // If a designator has the form
1512 //
1513 // [ constant-expression ]
1514 //
1515 // then the current object (defined below) shall have array
1516 // type and the expression shall be an integer constant
1517 // expression. If the array is of unknown size, any
1518 // nonnegative value is valid.
1519 //
1520 // Additionally, cope with the GNU extension that permits
1521 // designators of the form
1522 //
1523 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001524 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001525 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001526 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 << CurrentObjectType;
1528 ++Index;
1529 return true;
1530 }
1531
1532 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001533 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1534 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001535 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001536 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001537 DesignatedEndIndex = DesignatedStartIndex;
1538 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001539 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001540
Mike Stump1eb44332009-09-09 15:08:12 +00001541
1542 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001543 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001544 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001545 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001547
Chris Lattner3bf68932009-04-25 21:59:05 +00001548 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001549 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001550 }
1551
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552 if (isa<ConstantArrayType>(AT)) {
1553 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001554 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1555 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1556 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1557 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1558 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001559 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001560 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001561 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 << IndexExpr->getSourceRange();
1563 ++Index;
1564 return true;
1565 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001566 } else {
1567 // Make sure the bit-widths and signedness match.
1568 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1569 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001570 else if (DesignatedStartIndex.getBitWidth() <
1571 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001572 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1573 DesignatedStartIndex.setIsUnsigned(true);
1574 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Douglas Gregor4c678342009-01-28 21:54:33 +00001577 // Make sure that our non-designated initializer list has space
1578 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001579 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001580 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001581 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001582
Douglas Gregor34e79462009-01-28 23:36:17 +00001583 // Repeatedly perform subobject initializations in the range
1584 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001585
Douglas Gregor34e79462009-01-28 23:36:17 +00001586 // Move to the next designator
1587 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1588 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001589 while (DesignatedStartIndex <= DesignatedEndIndex) {
1590 // Recurse to check later designated subobjects.
1591 QualType ElementType = AT->getElementType();
1592 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001593 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1594 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001595 (DesignatedStartIndex == DesignatedEndIndex),
1596 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001597 return true;
1598
1599 // Move to the next index in the array that we'll be initializing.
1600 ++DesignatedStartIndex;
1601 ElementIndex = DesignatedStartIndex.getZExtValue();
1602 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001603
1604 // If this the first designator, our caller will continue checking
1605 // the rest of this array subobject.
1606 if (IsFirstDesignator) {
1607 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001608 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001609 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001610 return false;
1611 }
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Douglas Gregor34e79462009-01-28 23:36:17 +00001613 if (!FinishSubobjectInit)
1614 return false;
1615
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001616 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001617 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001618 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001619 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001620 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001621}
1622
Douglas Gregor4c678342009-01-28 21:54:33 +00001623// Get the structured initializer list for a subobject of type
1624// @p CurrentObjectType.
1625InitListExpr *
1626InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1627 QualType CurrentObjectType,
1628 InitListExpr *StructuredList,
1629 unsigned StructuredIndex,
1630 SourceRange InitRange) {
1631 Expr *ExistingInit = 0;
1632 if (!StructuredList)
1633 ExistingInit = SyntacticToSemantic[IList];
1634 else if (StructuredIndex < StructuredList->getNumInits())
1635 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor4c678342009-01-28 21:54:33 +00001637 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1638 return Result;
1639
1640 if (ExistingInit) {
1641 // We are creating an initializer list that initializes the
1642 // subobjects of the current object, but there was already an
1643 // initialization that completely initialized the current
1644 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001645 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001646 // struct X { int a, b; };
1647 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001648 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001649 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1650 // designated initializer re-initializes the whole
1651 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001652 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001653 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001654 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001655 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001656 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001657 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001658 << ExistingInit->getSourceRange();
1659 }
1660
Mike Stump1eb44332009-09-09 15:08:12 +00001661 InitListExpr *Result
1662 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001663 InitRange.getEnd());
1664
Douglas Gregor4c678342009-01-28 21:54:33 +00001665 Result->setType(CurrentObjectType);
1666
Douglas Gregorfa219202009-03-20 23:58:33 +00001667 // Pre-allocate storage for the structured initializer list.
1668 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001669 unsigned NumInits = 0;
1670 if (!StructuredList)
1671 NumInits = IList->getNumInits();
1672 else if (Index < IList->getNumInits()) {
1673 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1674 NumInits = SubList->getNumInits();
1675 }
1676
Mike Stump1eb44332009-09-09 15:08:12 +00001677 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001678 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1679 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1680 NumElements = CAType->getSize().getZExtValue();
1681 // Simple heuristic so that we don't allocate a very large
1682 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001683 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001684 NumElements = 0;
1685 }
John McCall183700f2009-09-21 23:43:11 +00001686 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001687 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001688 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001689 RecordDecl *RDecl = RType->getDecl();
1690 if (RDecl->isUnion())
1691 NumElements = 1;
1692 else
Mike Stump1eb44332009-09-09 15:08:12 +00001693 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001694 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001695 }
1696
Douglas Gregor08457732009-03-21 18:13:52 +00001697 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001698 NumElements = IList->getNumInits();
1699
1700 Result->reserveInits(NumElements);
1701
Douglas Gregor4c678342009-01-28 21:54:33 +00001702 // Link this new initializer list into the structured initializer
1703 // lists.
1704 if (StructuredList)
1705 StructuredList->updateInit(StructuredIndex, Result);
1706 else {
1707 Result->setSyntacticForm(IList);
1708 SyntacticToSemantic[IList] = Result;
1709 }
1710
1711 return Result;
1712}
1713
1714/// Update the initializer at index @p StructuredIndex within the
1715/// structured initializer list to the value @p expr.
1716void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1717 unsigned &StructuredIndex,
1718 Expr *expr) {
1719 // No structured initializer list to update
1720 if (!StructuredList)
1721 return;
1722
1723 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1724 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001725 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001726 diag::warn_initializer_overrides)
1727 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001728 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001729 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001730 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001731 << PrevInit->getSourceRange();
1732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Douglas Gregor4c678342009-01-28 21:54:33 +00001734 ++StructuredIndex;
1735}
1736
Douglas Gregor05c13a32009-01-22 00:58:24 +00001737/// Check that the given Index expression is a valid array designator
1738/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001739/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001740/// and produces a reasonable diagnostic if there is a
1741/// failure. Returns true if there was an error, false otherwise. If
1742/// everything went okay, Value will receive the value of the constant
1743/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001744static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001745CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001746 SourceLocation Loc = Index->getSourceRange().getBegin();
1747
1748 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001749 if (S.VerifyIntegerConstantExpression(Index, &Value))
1750 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001751
Chris Lattner3bf68932009-04-25 21:59:05 +00001752 if (Value.isSigned() && Value.isNegative())
1753 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001754 << Value.toString(10) << Index->getSourceRange();
1755
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001756 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001757 return false;
1758}
1759
1760Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1761 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001762 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001763 OwningExprResult Init) {
1764 typedef DesignatedInitExpr::Designator ASTDesignator;
1765
1766 bool Invalid = false;
1767 llvm::SmallVector<ASTDesignator, 32> Designators;
1768 llvm::SmallVector<Expr *, 32> InitExpressions;
1769
1770 // Build designators and check array designator expressions.
1771 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1772 const Designator &D = Desig.getDesignator(Idx);
1773 switch (D.getKind()) {
1774 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001775 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001776 D.getFieldLoc()));
1777 break;
1778
1779 case Designator::ArrayDesignator: {
1780 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1781 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001782 if (!Index->isTypeDependent() &&
1783 !Index->isValueDependent() &&
1784 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001785 Invalid = true;
1786 else {
1787 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001788 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001789 D.getRBracketLoc()));
1790 InitExpressions.push_back(Index);
1791 }
1792 break;
1793 }
1794
1795 case Designator::ArrayRangeDesignator: {
1796 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1797 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1798 llvm::APSInt StartValue;
1799 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001800 bool StartDependent = StartIndex->isTypeDependent() ||
1801 StartIndex->isValueDependent();
1802 bool EndDependent = EndIndex->isTypeDependent() ||
1803 EndIndex->isValueDependent();
1804 if ((!StartDependent &&
1805 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1806 (!EndDependent &&
1807 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001808 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001809 else {
1810 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001811 if (StartDependent || EndDependent) {
1812 // Nothing to compute.
1813 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001814 EndValue.extend(StartValue.getBitWidth());
1815 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1816 StartValue.extend(EndValue.getBitWidth());
1817
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001818 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001819 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001820 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001821 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1822 Invalid = true;
1823 } else {
1824 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001825 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001826 D.getEllipsisLoc(),
1827 D.getRBracketLoc()));
1828 InitExpressions.push_back(StartIndex);
1829 InitExpressions.push_back(EndIndex);
1830 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001831 }
1832 break;
1833 }
1834 }
1835 }
1836
1837 if (Invalid || Init.isInvalid())
1838 return ExprError();
1839
1840 // Clear out the expressions within the designation.
1841 Desig.ClearExprs(*this);
1842
1843 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001844 = DesignatedInitExpr::Create(Context,
1845 Designators.data(), Designators.size(),
1846 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001847 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001848 return Owned(DIE);
1849}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001850
1851bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001852 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001853 if (!CheckInitList.HadError())
1854 InitList = CheckInitList.getFullyStructuredList();
1855
1856 return CheckInitList.HadError();
1857}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001858
1859/// \brief Diagnose any semantic errors with value-initialization of
1860/// the given type.
1861///
1862/// Value-initialization effectively zero-initializes any types
1863/// without user-declared constructors, and calls the default
1864/// constructor for a for any type that has a user-declared
1865/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1866/// a type with a user-declared constructor does not have an
1867/// accessible, non-deleted default constructor. In C, everything can
1868/// be value-initialized, which corresponds to C's notion of
1869/// initializing objects with static storage duration when no
Mike Stump1eb44332009-09-09 15:08:12 +00001870/// initializer is provided for that object.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001871///
1872/// \returns true if there was an error, false otherwise.
1873bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1874 // C++ [dcl.init]p5:
1875 //
1876 // To value-initialize an object of type T means:
1877
1878 // -- if T is an array type, then each element is value-initialized;
1879 if (const ArrayType *AT = Context.getAsArrayType(Type))
1880 return CheckValueInitialization(AT->getElementType(), Loc);
1881
Ted Kremenek6217b802009-07-29 21:53:49 +00001882 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001883 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001884 // -- if T is a class type (clause 9) with a user-declared
1885 // constructor (12.1), then the default constructor for T is
1886 // called (and the initialization is ill-formed if T has no
1887 // accessible default constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00001888 if (ClassDecl->hasUserDeclaredConstructor()) {
1889 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1890
Douglas Gregor20093b42009-12-09 23:02:17 +00001891 // FIXME: Poor location information
Douglas Gregor39da0b82009-09-09 23:08:42 +00001892 CXXConstructorDecl *Constructor
1893 = PerformInitializationByConstructor(Type,
1894 MultiExprArg(*this, 0, 0),
1895 Loc, SourceRange(Loc),
1896 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +00001897 InitializationKind::CreateValue(Loc, Loc, Loc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001898 ConstructorArgs);
1899 if (!Constructor)
1900 return true;
1901
1902 OwningExprResult Init
1903 = BuildCXXConstructExpr(Loc, Type, Constructor,
1904 move_arg(ConstructorArgs));
1905 if (Init.isInvalid())
1906 return true;
1907
1908 // FIXME: Actually perform the value-initialization!
1909 return false;
1910 }
Douglas Gregor87fd7032009-02-02 17:43:21 +00001911 }
1912 }
1913
1914 if (Type->isReferenceType()) {
1915 // C++ [dcl.init]p5:
1916 // [...] A program that calls for default-initialization or
1917 // value-initialization of an entity of reference type is
1918 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001919 // FIXME: Once we have code that goes through this path, add an actual
1920 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001921 }
1922
1923 return false;
1924}
Douglas Gregor20093b42009-12-09 23:02:17 +00001925
1926//===----------------------------------------------------------------------===//
1927// Initialization entity
1928//===----------------------------------------------------------------------===//
1929
1930void InitializedEntity::InitDeclLoc() {
1931 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1932 "InitDeclLoc cannot be used with non-declaration entities.");
1933
1934 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1935 TL = DI->getTypeLoc();
1936 return;
1937 }
1938
1939 // FIXME: Once we've gone through the effort to create the fake
1940 // TypeSourceInfo, should we cache it in the declaration?
1941 // (If not, we "leak" it).
1942 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1943 .CreateTypeSourceInfo(VariableOrMember->getType());
1944 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1945 TL = DI->getTypeLoc();
1946}
1947
1948InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1949 CXXBaseSpecifier *Base)
1950{
1951 InitializedEntity Result;
1952 Result.Kind = EK_Base;
1953 Result.Base = Base;
1954 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1955 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1956 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1957 Result.TL = DI->getTypeLoc();
1958 return Result;
1959}
1960
Douglas Gregor99a2e602009-12-16 01:38:02 +00001961DeclarationName InitializedEntity::getName() const {
1962 switch (getKind()) {
1963 case EK_Variable:
1964 case EK_Parameter:
1965 case EK_Member:
1966 return VariableOrMember->getDeclName();
1967
1968 case EK_Result:
1969 case EK_Exception:
1970 case EK_Temporary:
1971 case EK_Base:
1972 return DeclarationName();
1973 }
1974
1975 // Silence GCC warning
1976 return DeclarationName();
1977}
1978
Douglas Gregor20093b42009-12-09 23:02:17 +00001979//===----------------------------------------------------------------------===//
1980// Initialization sequence
1981//===----------------------------------------------------------------------===//
1982
1983void InitializationSequence::Step::Destroy() {
1984 switch (Kind) {
1985 case SK_ResolveAddressOfOverloadedFunction:
1986 case SK_CastDerivedToBaseRValue:
1987 case SK_CastDerivedToBaseLValue:
1988 case SK_BindReference:
1989 case SK_BindReferenceToTemporary:
1990 case SK_UserConversion:
1991 case SK_QualificationConversionRValue:
1992 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001993 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001994 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001995 case SK_ZeroInitialization:
Douglas Gregor20093b42009-12-09 23:02:17 +00001996 break;
1997
1998 case SK_ConversionSequence:
1999 delete ICS;
2000 }
2001}
2002
2003void InitializationSequence::AddAddressOverloadResolutionStep(
2004 FunctionDecl *Function) {
2005 Step S;
2006 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2007 S.Type = Function->getType();
2008 S.Function = Function;
2009 Steps.push_back(S);
2010}
2011
2012void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2013 bool IsLValue) {
2014 Step S;
2015 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2016 S.Type = BaseType;
2017 Steps.push_back(S);
2018}
2019
2020void InitializationSequence::AddReferenceBindingStep(QualType T,
2021 bool BindingTemporary) {
2022 Step S;
2023 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2024 S.Type = T;
2025 Steps.push_back(S);
2026}
2027
Eli Friedman03981012009-12-11 02:42:07 +00002028void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2029 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002030 Step S;
2031 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002032 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002033 S.Function = Function;
2034 Steps.push_back(S);
2035}
2036
2037void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2038 bool IsLValue) {
2039 Step S;
2040 S.Kind = IsLValue? SK_QualificationConversionLValue
2041 : SK_QualificationConversionRValue;
2042 S.Type = Ty;
2043 Steps.push_back(S);
2044}
2045
2046void InitializationSequence::AddConversionSequenceStep(
2047 const ImplicitConversionSequence &ICS,
2048 QualType T) {
2049 Step S;
2050 S.Kind = SK_ConversionSequence;
2051 S.Type = T;
2052 S.ICS = new ImplicitConversionSequence(ICS);
2053 Steps.push_back(S);
2054}
2055
Douglas Gregord87b61f2009-12-10 17:56:55 +00002056void InitializationSequence::AddListInitializationStep(QualType T) {
2057 Step S;
2058 S.Kind = SK_ListInitialization;
2059 S.Type = T;
2060 Steps.push_back(S);
2061}
2062
Douglas Gregor51c56d62009-12-14 20:49:26 +00002063void
2064InitializationSequence::AddConstructorInitializationStep(
2065 CXXConstructorDecl *Constructor,
2066 QualType T) {
2067 Step S;
2068 S.Kind = SK_ConstructorInitialization;
2069 S.Type = T;
2070 S.Function = Constructor;
2071 Steps.push_back(S);
2072}
2073
Douglas Gregor71d17402009-12-15 00:01:57 +00002074void InitializationSequence::AddZeroInitializationStep(QualType T) {
2075 Step S;
2076 S.Kind = SK_ZeroInitialization;
2077 S.Type = T;
2078 Steps.push_back(S);
2079}
2080
Douglas Gregor20093b42009-12-09 23:02:17 +00002081void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2082 OverloadingResult Result) {
2083 SequenceKind = FailedSequence;
2084 this->Failure = Failure;
2085 this->FailedOverloadResult = Result;
2086}
2087
2088//===----------------------------------------------------------------------===//
2089// Attempt initialization
2090//===----------------------------------------------------------------------===//
2091
2092/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002093static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002094 const InitializedEntity &Entity,
2095 const InitializationKind &Kind,
2096 InitListExpr *InitList,
2097 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002098 // FIXME: We only perform rudimentary checking of list
2099 // initializations at this point, then assume that any list
2100 // initialization of an array, aggregate, or scalar will be
2101 // well-formed. We we actually "perform" list initialization, we'll
2102 // do all of the necessary checking. C++0x initializer lists will
2103 // force us to perform more checking here.
2104 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2105
2106 QualType DestType = Entity.getType().getType();
2107
2108 // C++ [dcl.init]p13:
2109 // If T is a scalar type, then a declaration of the form
2110 //
2111 // T x = { a };
2112 //
2113 // is equivalent to
2114 //
2115 // T x = a;
2116 if (DestType->isScalarType()) {
2117 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2118 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2119 return;
2120 }
2121
2122 // Assume scalar initialization from a single value works.
2123 } else if (DestType->isAggregateType()) {
2124 // Assume aggregate initialization works.
2125 } else if (DestType->isVectorType()) {
2126 // Assume vector initialization works.
2127 } else if (DestType->isReferenceType()) {
2128 // FIXME: C++0x defines behavior for this.
2129 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2130 return;
2131 } else if (DestType->isRecordType()) {
2132 // FIXME: C++0x defines behavior for this
2133 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2134 }
2135
2136 // Add a general "list initialization" step.
2137 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002138}
2139
2140/// \brief Try a reference initialization that involves calling a conversion
2141/// function.
2142///
2143/// FIXME: look intos DRs 656, 896
2144static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2145 const InitializedEntity &Entity,
2146 const InitializationKind &Kind,
2147 Expr *Initializer,
2148 bool AllowRValues,
2149 InitializationSequence &Sequence) {
2150 QualType DestType = Entity.getType().getType();
2151 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2152 QualType T1 = cv1T1.getUnqualifiedType();
2153 QualType cv2T2 = Initializer->getType();
2154 QualType T2 = cv2T2.getUnqualifiedType();
2155
2156 bool DerivedToBase;
2157 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2158 T1, T2, DerivedToBase) &&
2159 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002160 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002161
2162 // Build the candidate set directly in the initialization sequence
2163 // structure, so that it will persist if we fail.
2164 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2165 CandidateSet.clear();
2166
2167 // Determine whether we are allowed to call explicit constructors or
2168 // explicit conversion operators.
2169 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2170
2171 const RecordType *T1RecordType = 0;
2172 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2173 // The type we're converting to is a class type. Enumerate its constructors
2174 // to see if there is a suitable conversion.
2175 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2176
2177 DeclarationName ConstructorName
2178 = S.Context.DeclarationNames.getCXXConstructorName(
2179 S.Context.getCanonicalType(T1).getUnqualifiedType());
2180 DeclContext::lookup_iterator Con, ConEnd;
2181 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2182 Con != ConEnd; ++Con) {
2183 // Find the constructor (which may be a template).
2184 CXXConstructorDecl *Constructor = 0;
2185 FunctionTemplateDecl *ConstructorTmpl
2186 = dyn_cast<FunctionTemplateDecl>(*Con);
2187 if (ConstructorTmpl)
2188 Constructor = cast<CXXConstructorDecl>(
2189 ConstructorTmpl->getTemplatedDecl());
2190 else
2191 Constructor = cast<CXXConstructorDecl>(*Con);
2192
2193 if (!Constructor->isInvalidDecl() &&
2194 Constructor->isConvertingConstructor(AllowExplicit)) {
2195 if (ConstructorTmpl)
2196 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2197 &Initializer, 1, CandidateSet);
2198 else
2199 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2200 }
2201 }
2202 }
2203
2204 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2205 // The type we're converting from is a class type, enumerate its conversion
2206 // functions.
2207 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2208
2209 // Determine the type we are converting to. If we are allowed to
2210 // convert to an rvalue, take the type that the destination type
2211 // refers to.
2212 QualType ToType = AllowRValues? cv1T1 : DestType;
2213
2214 const UnresolvedSet *Conversions
2215 = T2RecordDecl->getVisibleConversionFunctions();
2216 for (UnresolvedSet::iterator I = Conversions->begin(),
2217 E = Conversions->end();
2218 I != E; ++I) {
2219 NamedDecl *D = *I;
2220 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2221 if (isa<UsingShadowDecl>(D))
2222 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2223
2224 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2225 CXXConversionDecl *Conv;
2226 if (ConvTemplate)
2227 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2228 else
2229 Conv = cast<CXXConversionDecl>(*I);
2230
2231 // If the conversion function doesn't return a reference type,
2232 // it can't be considered for this conversion unless we're allowed to
2233 // consider rvalues.
2234 // FIXME: Do we need to make sure that we only consider conversion
2235 // candidates with reference-compatible results? That might be needed to
2236 // break recursion.
2237 if ((AllowExplicit || !Conv->isExplicit()) &&
2238 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2239 if (ConvTemplate)
2240 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2241 ToType, CandidateSet);
2242 else
2243 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2244 CandidateSet);
2245 }
2246 }
2247 }
2248
2249 SourceLocation DeclLoc = Initializer->getLocStart();
2250
2251 // Perform overload resolution. If it fails, return the failed result.
2252 OverloadCandidateSet::iterator Best;
2253 if (OverloadingResult Result
2254 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2255 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002256
Douglas Gregor20093b42009-12-09 23:02:17 +00002257 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002258
2259 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002260 if (isa<CXXConversionDecl>(Function))
2261 T2 = Function->getResultType();
2262 else
2263 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002264
2265 // Add the user-defined conversion step.
2266 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2267
2268 // Determine whether we need to perform derived-to-base or
2269 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002270 bool NewDerivedToBase = false;
2271 Sema::ReferenceCompareResult NewRefRelationship
2272 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2273 NewDerivedToBase);
2274 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2275 "Overload resolution picked a bad conversion function");
2276 (void)NewRefRelationship;
2277 if (NewDerivedToBase)
2278 Sequence.AddDerivedToBaseCastStep(
2279 S.Context.getQualifiedType(T1,
2280 T2.getNonReferenceType().getQualifiers()),
2281 /*isLValue=*/true);
2282
2283 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2284 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2285
2286 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2287 return OR_Success;
2288}
2289
2290/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2291static void TryReferenceInitialization(Sema &S,
2292 const InitializedEntity &Entity,
2293 const InitializationKind &Kind,
2294 Expr *Initializer,
2295 InitializationSequence &Sequence) {
2296 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2297
2298 QualType DestType = Entity.getType().getType();
2299 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2300 QualType T1 = cv1T1.getUnqualifiedType();
2301 QualType cv2T2 = Initializer->getType();
2302 QualType T2 = cv2T2.getUnqualifiedType();
2303 SourceLocation DeclLoc = Initializer->getLocStart();
2304
2305 // If the initializer is the address of an overloaded function, try
2306 // to resolve the overloaded function. If all goes well, T2 is the
2307 // type of the resulting function.
2308 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2309 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2310 T1,
2311 false);
2312 if (!Fn) {
2313 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2314 return;
2315 }
2316
2317 Sequence.AddAddressOverloadResolutionStep(Fn);
2318 cv2T2 = Fn->getType();
2319 T2 = cv2T2.getUnqualifiedType();
2320 }
2321
2322 // FIXME: Rvalue references
2323 bool ForceRValue = false;
2324
2325 // Compute some basic properties of the types and the initializer.
2326 bool isLValueRef = DestType->isLValueReferenceType();
2327 bool isRValueRef = !isLValueRef;
2328 bool DerivedToBase = false;
2329 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2330 Initializer->isLvalue(S.Context);
2331 Sema::ReferenceCompareResult RefRelationship
2332 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2333
2334 // C++0x [dcl.init.ref]p5:
2335 // A reference to type "cv1 T1" is initialized by an expression of type
2336 // "cv2 T2" as follows:
2337 //
2338 // - If the reference is an lvalue reference and the initializer
2339 // expression
2340 OverloadingResult ConvOvlResult = OR_Success;
2341 if (isLValueRef) {
2342 if (InitLvalue == Expr::LV_Valid &&
2343 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2344 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2345 // reference-compatible with "cv2 T2," or
2346 //
2347 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2348 // bit-field when we're determining whether the reference initialization
2349 // can occur. This property will be checked by PerformInitialization.
2350 if (DerivedToBase)
2351 Sequence.AddDerivedToBaseCastStep(
2352 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2353 /*isLValue=*/true);
2354 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2355 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2356 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2357 return;
2358 }
2359
2360 // - has a class type (i.e., T2 is a class type), where T1 is not
2361 // reference-related to T2, and can be implicitly converted to an
2362 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2363 // with "cv3 T3" (this conversion is selected by enumerating the
2364 // applicable conversion functions (13.3.1.6) and choosing the best
2365 // one through overload resolution (13.3)),
2366 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2367 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2368 Initializer,
2369 /*AllowRValues=*/false,
2370 Sequence);
2371 if (ConvOvlResult == OR_Success)
2372 return;
2373 }
2374 }
2375
2376 // - Otherwise, the reference shall be an lvalue reference to a
2377 // non-volatile const type (i.e., cv1 shall be const), or the reference
2378 // shall be an rvalue reference and the initializer expression shall
2379 // be an rvalue.
2380 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2381 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2382 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2383 Sequence.SetOverloadFailure(
2384 InitializationSequence::FK_ReferenceInitOverloadFailed,
2385 ConvOvlResult);
2386 else if (isLValueRef)
2387 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2388 ? (RefRelationship == Sema::Ref_Related
2389 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2390 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2391 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2392 else
2393 Sequence.SetFailed(
2394 InitializationSequence::FK_RValueReferenceBindingToLValue);
2395
2396 return;
2397 }
2398
2399 // - If T1 and T2 are class types and
2400 if (T1->isRecordType() && T2->isRecordType()) {
2401 // - the initializer expression is an rvalue and "cv1 T1" is
2402 // reference-compatible with "cv2 T2", or
2403 if (InitLvalue != Expr::LV_Valid &&
2404 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2405 if (DerivedToBase)
2406 Sequence.AddDerivedToBaseCastStep(
2407 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2408 /*isLValue=*/false);
2409 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2410 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2411 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2412 return;
2413 }
2414
2415 // - T1 is not reference-related to T2 and the initializer expression
2416 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2417 // conversion is selected by enumerating the applicable conversion
2418 // functions (13.3.1.6) and choosing the best one through overload
2419 // resolution (13.3)),
2420 if (RefRelationship == Sema::Ref_Incompatible) {
2421 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2422 Kind, Initializer,
2423 /*AllowRValues=*/true,
2424 Sequence);
2425 if (ConvOvlResult)
2426 Sequence.SetOverloadFailure(
2427 InitializationSequence::FK_ReferenceInitOverloadFailed,
2428 ConvOvlResult);
2429
2430 return;
2431 }
2432
2433 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2434 return;
2435 }
2436
2437 // - If the initializer expression is an rvalue, with T2 an array type,
2438 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2439 // is bound to the object represented by the rvalue (see 3.10).
2440 // FIXME: How can an array type be reference-compatible with anything?
2441 // Don't we mean the element types of T1 and T2?
2442
2443 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2444 // from the initializer expression using the rules for a non-reference
2445 // copy initialization (8.5). The reference is then bound to the
2446 // temporary. [...]
2447 // Determine whether we are allowed to call explicit constructors or
2448 // explicit conversion operators.
2449 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2450 ImplicitConversionSequence ICS
2451 = S.TryImplicitConversion(Initializer, cv1T1,
2452 /*SuppressUserConversions=*/false, AllowExplicit,
2453 /*ForceRValue=*/false,
2454 /*FIXME:InOverloadResolution=*/false,
2455 /*UserCast=*/Kind.isExplicitCast());
2456
2457 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2458 // FIXME: Use the conversion function set stored in ICS to turn
2459 // this into an overloading ambiguity diagnostic. However, we need
2460 // to keep that set as an OverloadCandidateSet rather than as some
2461 // other kind of set.
2462 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
2463 return;
2464 }
2465
2466 // [...] If T1 is reference-related to T2, cv1 must be the
2467 // same cv-qualification as, or greater cv-qualification
2468 // than, cv2; otherwise, the program is ill-formed.
2469 if (RefRelationship == Sema::Ref_Related &&
2470 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2471 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2472 return;
2473 }
2474
2475 // Perform the actual conversion.
2476 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2477 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2478 return;
2479}
2480
2481/// \brief Attempt character array initialization from a string literal
2482/// (C++ [dcl.init.string], C99 6.7.8).
2483static void TryStringLiteralInitialization(Sema &S,
2484 const InitializedEntity &Entity,
2485 const InitializationKind &Kind,
2486 Expr *Initializer,
2487 InitializationSequence &Sequence) {
2488 // FIXME: Implement!
2489}
2490
Douglas Gregor20093b42009-12-09 23:02:17 +00002491/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2492/// enumerates the constructors of the initialized entity and performs overload
2493/// resolution to select the best.
2494static void TryConstructorInitialization(Sema &S,
2495 const InitializedEntity &Entity,
2496 const InitializationKind &Kind,
2497 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002498 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002499 InitializationSequence &Sequence) {
Douglas Gregora6ca6502009-12-14 20:57:13 +00002500 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002501
2502 // Build the candidate set directly in the initialization sequence
2503 // structure, so that it will persist if we fail.
2504 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2505 CandidateSet.clear();
2506
2507 // Determine whether we are allowed to call explicit constructors or
2508 // explicit conversion operators.
2509 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2510 Kind.getKind() == InitializationKind::IK_Value ||
2511 Kind.getKind() == InitializationKind::IK_Default);
2512
2513 // The type we're converting to is a class type. Enumerate its constructors
2514 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002515 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2516 assert(DestRecordType && "Constructor initialization requires record type");
2517 CXXRecordDecl *DestRecordDecl
2518 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2519
2520 DeclarationName ConstructorName
2521 = S.Context.DeclarationNames.getCXXConstructorName(
2522 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2523 DeclContext::lookup_iterator Con, ConEnd;
2524 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2525 Con != ConEnd; ++Con) {
2526 // Find the constructor (which may be a template).
2527 CXXConstructorDecl *Constructor = 0;
2528 FunctionTemplateDecl *ConstructorTmpl
2529 = dyn_cast<FunctionTemplateDecl>(*Con);
2530 if (ConstructorTmpl)
2531 Constructor = cast<CXXConstructorDecl>(
2532 ConstructorTmpl->getTemplatedDecl());
2533 else
2534 Constructor = cast<CXXConstructorDecl>(*Con);
2535
2536 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002537 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002538 if (ConstructorTmpl)
2539 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2540 Args, NumArgs, CandidateSet);
2541 else
2542 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2543 }
2544 }
2545
2546 SourceLocation DeclLoc = Kind.getLocation();
2547
2548 // Perform overload resolution. If it fails, return the failed result.
2549 OverloadCandidateSet::iterator Best;
2550 if (OverloadingResult Result
2551 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2552 Sequence.SetOverloadFailure(
2553 InitializationSequence::FK_ConstructorOverloadFailed,
2554 Result);
2555 return;
2556 }
2557
2558 // Add the constructor initialization step. Any cv-qualification conversion is
2559 // subsumed by the initialization.
2560 Sequence.AddConstructorInitializationStep(
2561 cast<CXXConstructorDecl>(Best->Function),
2562 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002563}
2564
Douglas Gregor71d17402009-12-15 00:01:57 +00002565/// \brief Attempt value initialization (C++ [dcl.init]p7).
2566static void TryValueInitialization(Sema &S,
2567 const InitializedEntity &Entity,
2568 const InitializationKind &Kind,
2569 InitializationSequence &Sequence) {
2570 // C++ [dcl.init]p5:
2571 //
2572 // To value-initialize an object of type T means:
2573 QualType T = Entity.getType().getType();
2574
2575 // -- if T is an array type, then each element is value-initialized;
2576 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2577 T = AT->getElementType();
2578
2579 if (const RecordType *RT = T->getAs<RecordType>()) {
2580 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2581 // -- if T is a class type (clause 9) with a user-declared
2582 // constructor (12.1), then the default constructor for T is
2583 // called (and the initialization is ill-formed if T has no
2584 // accessible default constructor);
2585 //
2586 // FIXME: we really want to refer to a single subobject of the array,
2587 // but Entity doesn't have a way to capture that (yet).
2588 if (ClassDecl->hasUserDeclaredConstructor())
2589 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2590
2591 // FIXME: non-union class type w/ non-trivial default constructor gets
2592 // zero-initialized, then constructor gets called.
2593 }
2594 }
2595
2596 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2597 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2598}
2599
Douglas Gregor99a2e602009-12-16 01:38:02 +00002600/// \brief Attempt default initialization (C++ [dcl.init]p6).
2601static void TryDefaultInitialization(Sema &S,
2602 const InitializedEntity &Entity,
2603 const InitializationKind &Kind,
2604 InitializationSequence &Sequence) {
2605 assert(Kind.getKind() == InitializationKind::IK_Default);
2606
2607 // C++ [dcl.init]p6:
2608 // To default-initialize an object of type T means:
2609 // - if T is an array type, each element is default-initialized;
2610 QualType DestType = Entity.getType().getType();
2611 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2612 DestType = Array->getElementType();
2613
2614 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2615 // constructor for T is called (and the initialization is ill-formed if
2616 // T has no accessible default constructor);
2617 if (DestType->isRecordType()) {
2618 // FIXME: If a program calls for the default initialization of an object of
2619 // a const-qualified type T, T shall be a class type with a user-provided
2620 // default constructor.
2621 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2622 Sequence);
2623 }
2624
2625 // - otherwise, no initialization is performed.
2626 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2627
2628 // If a program calls for the default initialization of an object of
2629 // a const-qualified type T, T shall be a class type with a user-provided
2630 // default constructor.
2631 if (DestType.isConstQualified())
2632 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2633}
2634
Douglas Gregor20093b42009-12-09 23:02:17 +00002635/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2636/// which enumerates all conversion functions and performs overload resolution
2637/// to select the best.
2638static void TryUserDefinedConversion(Sema &S,
2639 const InitializedEntity &Entity,
2640 const InitializationKind &Kind,
2641 Expr *Initializer,
2642 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002643 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2644
2645 QualType DestType = Entity.getType().getType();
2646 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2647 QualType SourceType = Initializer->getType();
2648 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2649 "Must have a class type to perform a user-defined conversion");
2650
2651 // Build the candidate set directly in the initialization sequence
2652 // structure, so that it will persist if we fail.
2653 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2654 CandidateSet.clear();
2655
2656 // Determine whether we are allowed to call explicit constructors or
2657 // explicit conversion operators.
2658 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2659
2660 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2661 // The type we're converting to is a class type. Enumerate its constructors
2662 // to see if there is a suitable conversion.
2663 CXXRecordDecl *DestRecordDecl
2664 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2665
2666 DeclarationName ConstructorName
2667 = S.Context.DeclarationNames.getCXXConstructorName(
2668 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2669 DeclContext::lookup_iterator Con, ConEnd;
2670 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2671 Con != ConEnd; ++Con) {
2672 // Find the constructor (which may be a template).
2673 CXXConstructorDecl *Constructor = 0;
2674 FunctionTemplateDecl *ConstructorTmpl
2675 = dyn_cast<FunctionTemplateDecl>(*Con);
2676 if (ConstructorTmpl)
2677 Constructor = cast<CXXConstructorDecl>(
2678 ConstructorTmpl->getTemplatedDecl());
2679 else
2680 Constructor = cast<CXXConstructorDecl>(*Con);
2681
2682 if (!Constructor->isInvalidDecl() &&
2683 Constructor->isConvertingConstructor(AllowExplicit)) {
2684 if (ConstructorTmpl)
2685 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2686 &Initializer, 1, CandidateSet);
2687 else
2688 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2689 }
2690 }
2691 }
2692
2693 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2694 // The type we're converting from is a class type, enumerate its conversion
2695 // functions.
2696 CXXRecordDecl *SourceRecordDecl
2697 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2698
2699 const UnresolvedSet *Conversions
2700 = SourceRecordDecl->getVisibleConversionFunctions();
2701 for (UnresolvedSet::iterator I = Conversions->begin(),
2702 E = Conversions->end();
2703 I != E; ++I) {
2704 NamedDecl *D = *I;
2705 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2706 if (isa<UsingShadowDecl>(D))
2707 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2708
2709 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2710 CXXConversionDecl *Conv;
2711 if (ConvTemplate)
2712 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2713 else
2714 Conv = cast<CXXConversionDecl>(*I);
2715
2716 if (AllowExplicit || !Conv->isExplicit()) {
2717 if (ConvTemplate)
2718 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2719 DestType, CandidateSet);
2720 else
2721 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2722 CandidateSet);
2723 }
2724 }
2725 }
2726
2727 SourceLocation DeclLoc = Initializer->getLocStart();
2728
2729 // Perform overload resolution. If it fails, return the failed result.
2730 OverloadCandidateSet::iterator Best;
2731 if (OverloadingResult Result
2732 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2733 Sequence.SetOverloadFailure(
2734 InitializationSequence::FK_UserConversionOverloadFailed,
2735 Result);
2736 return;
2737 }
2738
2739 FunctionDecl *Function = Best->Function;
2740
2741 if (isa<CXXConstructorDecl>(Function)) {
2742 // Add the user-defined conversion step. Any cv-qualification conversion is
2743 // subsumed by the initialization.
2744 Sequence.AddUserConversionStep(Function, DestType);
2745 return;
2746 }
2747
2748 // Add the user-defined conversion step that calls the conversion function.
2749 QualType ConvType = Function->getResultType().getNonReferenceType();
2750 Sequence.AddUserConversionStep(Function, ConvType);
2751
2752 // If the conversion following the call to the conversion function is
2753 // interesting, add it as a separate step.
2754 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2755 Best->FinalConversion.Third) {
2756 ImplicitConversionSequence ICS;
2757 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2758 ICS.Standard = Best->FinalConversion;
2759 Sequence.AddConversionSequenceStep(ICS, DestType);
2760 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002761}
2762
2763/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2764/// non-class type to another.
2765static void TryImplicitConversion(Sema &S,
2766 const InitializedEntity &Entity,
2767 const InitializationKind &Kind,
2768 Expr *Initializer,
2769 InitializationSequence &Sequence) {
2770 ImplicitConversionSequence ICS
2771 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2772 /*SuppressUserConversions=*/true,
2773 /*AllowExplicit=*/false,
2774 /*ForceRValue=*/false,
2775 /*FIXME:InOverloadResolution=*/false,
2776 /*UserCast=*/Kind.isExplicitCast());
2777
2778 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2779 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2780 return;
2781 }
2782
2783 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2784}
2785
2786InitializationSequence::InitializationSequence(Sema &S,
2787 const InitializedEntity &Entity,
2788 const InitializationKind &Kind,
2789 Expr **Args,
2790 unsigned NumArgs) {
2791 ASTContext &Context = S.Context;
2792
2793 // C++0x [dcl.init]p16:
2794 // The semantics of initializers are as follows. The destination type is
2795 // the type of the object or reference being initialized and the source
2796 // type is the type of the initializer expression. The source type is not
2797 // defined when the initializer is a braced-init-list or when it is a
2798 // parenthesized list of expressions.
2799 QualType DestType = Entity.getType().getType();
2800
2801 if (DestType->isDependentType() ||
2802 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2803 SequenceKind = DependentSequence;
2804 return;
2805 }
2806
2807 QualType SourceType;
2808 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002809 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002810 Initializer = Args[0];
2811 if (!isa<InitListExpr>(Initializer))
2812 SourceType = Initializer->getType();
2813 }
2814
2815 // - If the initializer is a braced-init-list, the object is
2816 // list-initialized (8.5.4).
2817 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2818 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002819 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002820 }
2821
2822 // - If the destination type is a reference type, see 8.5.3.
2823 if (DestType->isReferenceType()) {
2824 // C++0x [dcl.init.ref]p1:
2825 // A variable declared to be a T& or T&&, that is, "reference to type T"
2826 // (8.3.2), shall be initialized by an object, or function, of type T or
2827 // by an object that can be converted into a T.
2828 // (Therefore, multiple arguments are not permitted.)
2829 if (NumArgs != 1)
2830 SetFailed(FK_TooManyInitsForReference);
2831 else
2832 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2833 return;
2834 }
2835
2836 // - If the destination type is an array of characters, an array of
2837 // char16_t, an array of char32_t, or an array of wchar_t, and the
2838 // initializer is a string literal, see 8.5.2.
2839 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2840 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2841 return;
2842 }
2843
2844 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002845 if (Kind.getKind() == InitializationKind::IK_Value ||
2846 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002847 TryValueInitialization(S, Entity, Kind, *this);
2848 return;
2849 }
2850
Douglas Gregor99a2e602009-12-16 01:38:02 +00002851 // Handle default initialization.
2852 if (Kind.getKind() == InitializationKind::IK_Default){
2853 TryDefaultInitialization(S, Entity, Kind, *this);
2854 return;
2855 }
2856
Douglas Gregor20093b42009-12-09 23:02:17 +00002857 // - Otherwise, if the destination type is an array, the program is
2858 // ill-formed.
2859 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2860 if (AT->getElementType()->isAnyCharacterType())
2861 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2862 else
2863 SetFailed(FK_ArrayNeedsInitList);
2864
2865 return;
2866 }
2867
2868 // - If the destination type is a (possibly cv-qualified) class type:
2869 if (DestType->isRecordType()) {
2870 // - If the initialization is direct-initialization, or if it is
2871 // copy-initialization where the cv-unqualified version of the
2872 // source type is the same class as, or a derived class of, the
2873 // class of the destination, constructors are considered. [...]
2874 if (Kind.getKind() == InitializationKind::IK_Direct ||
2875 (Kind.getKind() == InitializationKind::IK_Copy &&
2876 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2877 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002878 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2879 Entity.getType().getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002880 // - Otherwise (i.e., for the remaining copy-initialization cases),
2881 // user-defined conversion sequences that can convert from the source
2882 // type to the destination type or (when a conversion function is
2883 // used) to a derived class thereof are enumerated as described in
2884 // 13.3.1.4, and the best one is chosen through overload resolution
2885 // (13.3).
2886 else
2887 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2888 return;
2889 }
2890
Douglas Gregor99a2e602009-12-16 01:38:02 +00002891 if (NumArgs > 1) {
2892 SetFailed(FK_TooManyInitsForScalar);
2893 return;
2894 }
2895 assert(NumArgs == 1 && "Zero-argument case handled above");
2896
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 // - Otherwise, if the source type is a (possibly cv-qualified) class
2898 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002899 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002900 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2901 return;
2902 }
2903
2904 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002905 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002906 // conversions (Clause 4) will be used, if necessary, to convert the
2907 // initializer expression to the cv-unqualified version of the
2908 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002909 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002910 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2911}
2912
2913InitializationSequence::~InitializationSequence() {
2914 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2915 StepEnd = Steps.end();
2916 Step != StepEnd; ++Step)
2917 Step->Destroy();
2918}
2919
2920//===----------------------------------------------------------------------===//
2921// Perform initialization
2922//===----------------------------------------------------------------------===//
2923
2924Action::OwningExprResult
2925InitializationSequence::Perform(Sema &S,
2926 const InitializedEntity &Entity,
2927 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00002928 Action::MultiExprArg Args,
2929 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002930 if (SequenceKind == FailedSequence) {
2931 unsigned NumArgs = Args.size();
2932 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
2933 return S.ExprError();
2934 }
2935
2936 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002937 // If the declaration is a non-dependent, incomplete array type
2938 // that has an initializer, then its type will be completed once
2939 // the initializer is instantiated.
2940 if (ResultType && !Entity.getType().getType()->isDependentType() &&
2941 Args.size() == 1) {
2942 QualType DeclType = Entity.getType().getType();
2943 if (const IncompleteArrayType *ArrayT
2944 = S.Context.getAsIncompleteArrayType(DeclType)) {
2945 // FIXME: We don't currently have the ability to accurately
2946 // compute the length of an initializer list without
2947 // performing full type-checking of the initializer list
2948 // (since we have to determine where braces are implicitly
2949 // introduced and such). So, we fall back to making the array
2950 // type a dependently-sized array type with no specified
2951 // bound.
2952 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
2953 SourceRange Brackets;
2954 // Scavange the location of the brackets from the entity, if we can.
2955 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
2956 IncompleteArrayTypeLoc ArrayLoc
2957 = cast<IncompleteArrayTypeLoc>(Entity.getType());
2958 Brackets = ArrayLoc.getBracketsRange();
2959 }
2960
2961 *ResultType
2962 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
2963 /*NumElts=*/0,
2964 ArrayT->getSizeModifier(),
2965 ArrayT->getIndexTypeCVRQualifiers(),
2966 Brackets);
2967 }
2968
2969 }
2970 }
2971
Douglas Gregor20093b42009-12-09 23:02:17 +00002972 if (Kind.getKind() == InitializationKind::IK_Copy)
2973 return Sema::OwningExprResult(S, Args.release()[0]);
2974
2975 unsigned NumArgs = Args.size();
2976 return S.Owned(new (S.Context) ParenListExpr(S.Context,
2977 SourceLocation(),
2978 (Expr **)Args.release(),
2979 NumArgs,
2980 SourceLocation()));
2981 }
2982
Douglas Gregor99a2e602009-12-16 01:38:02 +00002983 if (SequenceKind == NoInitialization)
2984 return S.Owned((Expr *)0);
2985
Douglas Gregor20093b42009-12-09 23:02:17 +00002986 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002987 if (ResultType)
2988 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002989
Douglas Gregor99a2e602009-12-16 01:38:02 +00002990 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
2991
2992 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
2993
2994 // For initialization steps that start with a single initializer,
2995 // grab the only argument out the Args and place it into the "current"
2996 // initializer.
2997 switch (Steps.front().Kind) {
2998 case SK_ResolveAddressOfOverloadedFunction:
2999 case SK_CastDerivedToBaseRValue:
3000 case SK_CastDerivedToBaseLValue:
3001 case SK_BindReference:
3002 case SK_BindReferenceToTemporary:
3003 case SK_UserConversion:
3004 case SK_QualificationConversionLValue:
3005 case SK_QualificationConversionRValue:
3006 case SK_ConversionSequence:
3007 case SK_ListInitialization:
3008 assert(Args.size() == 1);
3009 CurInit = Sema::OwningExprResult(S,
3010 ((Expr **)(Args.get()))[0]->Retain());
3011 if (CurInit.isInvalid())
3012 return S.ExprError();
3013 break;
3014
3015 case SK_ConstructorInitialization:
3016 case SK_ZeroInitialization:
3017 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003018 }
3019
3020 // Walk through the computed steps for the initialization sequence,
3021 // performing the specified conversions along the way.
3022 for (step_iterator Step = step_begin(), StepEnd = step_end();
3023 Step != StepEnd; ++Step) {
3024 if (CurInit.isInvalid())
3025 return S.ExprError();
3026
3027 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003028 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003029
3030 switch (Step->Kind) {
3031 case SK_ResolveAddressOfOverloadedFunction:
3032 // Overload resolution determined which function invoke; update the
3033 // initializer to reflect that choice.
3034 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3035 break;
3036
3037 case SK_CastDerivedToBaseRValue:
3038 case SK_CastDerivedToBaseLValue: {
3039 // We have a derived-to-base cast that produces either an rvalue or an
3040 // lvalue. Perform that cast.
3041
3042 // Casts to inaccessible base classes are allowed with C-style casts.
3043 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3044 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3045 CurInitExpr->getLocStart(),
3046 CurInitExpr->getSourceRange(),
3047 IgnoreBaseAccess))
3048 return S.ExprError();
3049
3050 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3051 CastExpr::CK_DerivedToBase,
3052 (Expr*)CurInit.release(),
3053 Step->Kind == SK_CastDerivedToBaseLValue));
3054 break;
3055 }
3056
3057 case SK_BindReference:
3058 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3059 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3060 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3061 << Entity.getType().getType().isVolatileQualified()
3062 << BitField->getDeclName()
3063 << CurInitExpr->getSourceRange();
3064 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3065 return S.ExprError();
3066 }
3067
3068 // Reference binding does not have any corresponding ASTs.
3069
3070 // Check exception specifications
3071 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3072 return S.ExprError();
3073 break;
3074
3075 case SK_BindReferenceToTemporary:
3076 // Check exception specifications
3077 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3078 return S.ExprError();
3079
3080 // FIXME: At present, we have no AST to describe when we need to make a
3081 // temporary to bind a reference to. We should.
3082 break;
3083
3084 case SK_UserConversion: {
3085 // We have a user-defined conversion that invokes either a constructor
3086 // or a conversion function.
3087 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
3088 if (CXXConstructorDecl *Constructor
3089 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3090 // Build a call to the selected constructor.
3091 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3092 SourceLocation Loc = CurInitExpr->getLocStart();
3093 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3094
3095 // Determine the arguments required to actually perform the constructor
3096 // call.
3097 if (S.CompleteConstructorCall(Constructor,
3098 Sema::MultiExprArg(S,
3099 (void **)&CurInitExpr,
3100 1),
3101 Loc, ConstructorArgs))
3102 return S.ExprError();
3103
3104 // Build the an expression that constructs a temporary.
3105 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3106 move_arg(ConstructorArgs));
3107 if (CurInit.isInvalid())
3108 return S.ExprError();
3109
3110 CastKind = CastExpr::CK_ConstructorConversion;
3111 } else {
3112 // Build a call to the conversion function.
3113 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
3114
3115 // FIXME: Should we move this initialization into a separate
3116 // derived-to-base conversion? I believe the answer is "no", because
3117 // we don't want to turn off access control here for c-style casts.
3118 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3119 return S.ExprError();
3120
3121 // Do a little dance to make sure that CurInit has the proper
3122 // pointer.
3123 CurInit.release();
3124
3125 // Build the actual call to the conversion function.
3126 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3127 if (CurInit.isInvalid() || !CurInit.get())
3128 return S.ExprError();
3129
3130 CastKind = CastExpr::CK_UserDefinedConversion;
3131 }
3132
3133 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3134 CurInitExpr = CurInit.takeAs<Expr>();
3135 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3136 CastKind,
3137 CurInitExpr,
3138 false));
3139 break;
3140 }
3141
3142 case SK_QualificationConversionLValue:
3143 case SK_QualificationConversionRValue:
3144 // Perform a qualification conversion; these can never go wrong.
3145 S.ImpCastExprToType(CurInitExpr, Step->Type,
3146 CastExpr::CK_NoOp,
3147 Step->Kind == SK_QualificationConversionLValue);
3148 CurInit.release();
3149 CurInit = S.Owned(CurInitExpr);
3150 break;
3151
3152 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003153 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003154 false, false, *Step->ICS))
3155 return S.ExprError();
3156
3157 CurInit.release();
3158 CurInit = S.Owned(CurInitExpr);
3159 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003160
3161 case SK_ListInitialization: {
3162 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3163 QualType Ty = Step->Type;
3164 if (S.CheckInitList(InitList, ResultType? *ResultType : Ty))
3165 return S.ExprError();
3166
3167 CurInit.release();
3168 CurInit = S.Owned(InitList);
3169 break;
3170 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003171
3172 case SK_ConstructorInitialization: {
3173 CXXConstructorDecl *Constructor
3174 = cast<CXXConstructorDecl>(Step->Function);
3175
3176 // Build a call to the selected constructor.
3177 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3178 SourceLocation Loc = Kind.getLocation();
3179
3180 // Determine the arguments required to actually perform the constructor
3181 // call.
3182 if (S.CompleteConstructorCall(Constructor, move(Args),
3183 Loc, ConstructorArgs))
3184 return S.ExprError();
3185
3186 // Build the an expression that constructs a temporary.
3187 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3188 move_arg(ConstructorArgs));
3189 if (CurInit.isInvalid())
3190 return S.ExprError();
3191
Douglas Gregor51c56d62009-12-14 20:49:26 +00003192 break;
3193 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003194
3195 case SK_ZeroInitialization: {
3196 if (Kind.getKind() == InitializationKind::IK_Value)
3197 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3198 Kind.getRange().getBegin(),
3199 Kind.getRange().getEnd()));
3200 else
3201 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
3202 break;
3203 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003204 }
3205 }
3206
3207 return move(CurInit);
3208}
3209
3210//===----------------------------------------------------------------------===//
3211// Diagnose initialization failures
3212//===----------------------------------------------------------------------===//
3213bool InitializationSequence::Diagnose(Sema &S,
3214 const InitializedEntity &Entity,
3215 const InitializationKind &Kind,
3216 Expr **Args, unsigned NumArgs) {
3217 if (SequenceKind != FailedSequence)
3218 return false;
3219
3220 QualType DestType = Entity.getType().getType();
3221 switch (Failure) {
3222 case FK_TooManyInitsForReference:
3223 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3224 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3225 break;
3226
3227 case FK_ArrayNeedsInitList:
3228 case FK_ArrayNeedsInitListOrStringLiteral:
3229 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3230 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3231 break;
3232
3233 case FK_AddressOfOverloadFailed:
3234 S.ResolveAddressOfOverloadedFunction(Args[0],
3235 DestType.getNonReferenceType(),
3236 true);
3237 break;
3238
3239 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003240 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003241 switch (FailedOverloadResult) {
3242 case OR_Ambiguous:
3243 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3244 << Args[0]->getType() << DestType.getNonReferenceType()
3245 << Args[0]->getSourceRange();
3246 S.PrintOverloadCandidates(FailedCandidateSet, true);
3247 break;
3248
3249 case OR_No_Viable_Function:
3250 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3251 << Args[0]->getType() << DestType.getNonReferenceType()
3252 << Args[0]->getSourceRange();
3253 S.PrintOverloadCandidates(FailedCandidateSet, false);
3254 break;
3255
3256 case OR_Deleted: {
3257 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3258 << Args[0]->getType() << DestType.getNonReferenceType()
3259 << Args[0]->getSourceRange();
3260 OverloadCandidateSet::iterator Best;
3261 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3262 Kind.getLocation(),
3263 Best);
3264 if (Ovl == OR_Deleted) {
3265 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3266 << Best->Function->isDeleted();
3267 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003268 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 }
3270 break;
3271 }
3272
3273 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003274 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003275 break;
3276 }
3277 break;
3278
3279 case FK_NonConstLValueReferenceBindingToTemporary:
3280 case FK_NonConstLValueReferenceBindingToUnrelated:
3281 S.Diag(Kind.getLocation(),
3282 Failure == FK_NonConstLValueReferenceBindingToTemporary
3283 ? diag::err_lvalue_reference_bind_to_temporary
3284 : diag::err_lvalue_reference_bind_to_unrelated)
3285 << DestType.getNonReferenceType()
3286 << Args[0]->getType()
3287 << Args[0]->getSourceRange();
3288 break;
3289
3290 case FK_RValueReferenceBindingToLValue:
3291 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3292 << Args[0]->getSourceRange();
3293 break;
3294
3295 case FK_ReferenceInitDropsQualifiers:
3296 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3297 << DestType.getNonReferenceType()
3298 << Args[0]->getType()
3299 << Args[0]->getSourceRange();
3300 break;
3301
3302 case FK_ReferenceInitFailed:
3303 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3304 << DestType.getNonReferenceType()
3305 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3306 << Args[0]->getType()
3307 << Args[0]->getSourceRange();
3308 break;
3309
3310 case FK_ConversionFailed:
3311 S.Diag(Kind.getLocation(), diag::err_cannot_initialize_decl_noname)
3312 << DestType
3313 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3314 << Args[0]->getType()
3315 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003316 break;
3317
3318 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003319 SourceRange R;
3320
3321 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3322 R = SourceRange(InitList->getInit(1)->getLocStart(),
3323 InitList->getLocEnd());
3324 else
3325 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003326
3327 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003328 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003329 break;
3330 }
3331
3332 case FK_ReferenceBindingToInitList:
3333 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3334 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3335 break;
3336
3337 case FK_InitListBadDestinationType:
3338 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3339 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3340 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003341
3342 case FK_ConstructorOverloadFailed: {
3343 SourceRange ArgsRange;
3344 if (NumArgs)
3345 ArgsRange = SourceRange(Args[0]->getLocStart(),
3346 Args[NumArgs - 1]->getLocEnd());
3347
3348 // FIXME: Using "DestType" for the entity we're printing is probably
3349 // bad.
3350 switch (FailedOverloadResult) {
3351 case OR_Ambiguous:
3352 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3353 << DestType << ArgsRange;
3354 S.PrintOverloadCandidates(FailedCandidateSet, true);
3355 break;
3356
3357 case OR_No_Viable_Function:
3358 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3359 << DestType << ArgsRange;
3360 S.PrintOverloadCandidates(FailedCandidateSet, false);
3361 break;
3362
3363 case OR_Deleted: {
3364 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3365 << true << DestType << ArgsRange;
3366 OverloadCandidateSet::iterator Best;
3367 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3368 Kind.getLocation(),
3369 Best);
3370 if (Ovl == OR_Deleted) {
3371 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3372 << Best->Function->isDeleted();
3373 } else {
3374 llvm_unreachable("Inconsistent overload resolution?");
3375 }
3376 break;
3377 }
3378
3379 case OR_Success:
3380 llvm_unreachable("Conversion did not fail!");
3381 break;
3382 }
3383 break;
3384 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003385
3386 case FK_DefaultInitOfConst:
3387 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3388 << DestType;
3389 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003390 }
3391
3392 return true;
3393}