blob: bc7210c568acecb40a1b094df4d05a1816e8aaff [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-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 Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattnerd8b741c82009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnerd8b741c82009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Eli Friedman893abe42009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000089
Eli Friedman893abe42009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000097
Eli Friedman893abe42009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000103}
104
Chris Lattner0cb78032009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregorcde232f2009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000136namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000142
Anders Carlsson6cabf312010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000213
Douglas Gregor2bb07652009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner9ececce2009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000229
Douglas Gregor2bb07652009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
265 Sema::OwningExprResult MemberInit
266 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
267 Sema::MultiExprArg(SemaRef, 0, 0));
268 if (MemberInit.isInvalid()) {
269 hadError = true;
270 return;
271 }
272
273 if (hadError) {
274 // Do nothing
275 } else if (Init < NumInits) {
276 ILE->setInit(Init, MemberInit.takeAs<Expr>());
277 } else if (InitSeq.getKind()
278 == InitializationSequence::ConstructorInitialization) {
279 // Value-initialization requires a constructor call, so
280 // extend the initializer list to include the constructor
281 // call and make a note that we'll need to take another pass
282 // through the initializer list.
283 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
284 RequiresSecondPass = true;
285 }
286 } else if (InitListExpr *InnerILE
287 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
288 FillInValueInitializations(MemberEntity, InnerILE,
289 RequiresSecondPass);
290}
291
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000292/// Recursively replaces NULL values within the given initializer list
293/// with expressions that perform value-initialization of the
294/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000295void
296InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
297 InitListExpr *ILE,
298 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000299 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000300 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000301 SourceLocation Loc = ILE->getSourceRange().getBegin();
302 if (ILE->getSyntacticForm())
303 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000304
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000305 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000306 if (RType->getDecl()->isUnion() &&
307 ILE->getInitializedFieldInUnion())
308 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
309 Entity, ILE, RequiresSecondPass);
310 else {
311 unsigned Init = 0;
312 for (RecordDecl::field_iterator
313 Field = RType->getDecl()->field_begin(),
314 FieldEnd = RType->getDecl()->field_end();
315 Field != FieldEnd; ++Field) {
316 if (Field->isUnnamedBitfield())
317 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000318
Douglas Gregor2bb07652009-12-22 00:05:34 +0000319 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000320 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321
322 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
323 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000324 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325
Douglas Gregor2bb07652009-12-22 00:05:34 +0000326 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 // Only look at the first initialization of a union.
329 if (RType->getDecl()->isUnion())
330 break;
331 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000332 }
333
334 return;
Mike Stump11289f42009-09-09 15:08:12 +0000335 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000336
337 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000338
Douglas Gregor723796a2009-12-16 06:35:08 +0000339 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000340 unsigned NumInits = ILE->getNumInits();
341 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000342 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000343 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000344 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
345 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000346 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
347 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000348 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000349 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000350 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000351 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
352 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000353 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000354 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000355
Douglas Gregor723796a2009-12-16 06:35:08 +0000356
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000358 if (hadError)
359 return;
360
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000361 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
362 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000363 ElementEntity.setElementIndex(Init);
364
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000365 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000366 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
367 true);
368 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
369 if (!InitSeq) {
370 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000371 hadError = true;
372 return;
373 }
374
Douglas Gregor723796a2009-12-16 06:35:08 +0000375 Sema::OwningExprResult ElementInit
376 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
377 Sema::MultiExprArg(SemaRef, 0, 0));
378 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000379 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000380 return;
381 }
382
383 if (hadError) {
384 // Do nothing
385 } else if (Init < NumInits) {
386 ILE->setInit(Init, ElementInit.takeAs<Expr>());
387 } else if (InitSeq.getKind()
388 == InitializationSequence::ConstructorInitialization) {
389 // Value-initialization requires a constructor call, so
390 // extend the initializer list to include the constructor
391 // call and make a note that we'll need to take another pass
392 // through the initializer list.
393 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
394 RequiresSecondPass = true;
395 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000396 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 }
400}
401
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000402
Douglas Gregor723796a2009-12-16 06:35:08 +0000403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
404 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000405 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000406 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000407
Eli Friedman23a9e312008-05-19 19:16:24 +0000408 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000409 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000410 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000412 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000413 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000414 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000415
Douglas Gregor723796a2009-12-16 06:35:08 +0000416 if (!hadError) {
417 bool RequiresSecondPass = false;
418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000419 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 FillInValueInitializations(Entity, FullyStructuredList,
421 RequiresSecondPass);
422 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000423}
424
425int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000426 // FIXME: use a proper constant
427 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000428 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000429 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000430 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
431 }
432 return maxElements;
433}
434
435int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000437 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000438 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000439 Field = structDecl->field_begin(),
440 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000441 Field != FieldEnd; ++Field) {
442 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
443 ++InitializableMembers;
444 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000445 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000446 return std::min(InitializableMembers, 1);
447 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000448}
449
Anders Carlsson6cabf312010-01-23 23:23:01 +0000450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000451 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000452 QualType T, unsigned &Index,
453 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000454 unsigned &StructuredIndex,
455 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000456 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Steve Narofff8ecff22008-05-01 22:18:59 +0000458 if (T->isArrayType())
459 maxElements = numArrayElements(T);
460 else if (T->isStructureType() || T->isUnionType())
461 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000462 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000463 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 else
465 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000466
Eli Friedmane0f832b2008-05-25 13:49:22 +0000467 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000470 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000471 hadError = true;
472 return;
473 }
474
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000475 // Build a structured initializer list corresponding to this subobject.
476 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
478 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
480 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000481 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000482
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000484 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000485 CheckListElementTypes(Entity, ParentIList, T,
486 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000487 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000488 StructuredSubobjectInitIndex,
489 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000491 StructuredSubobjectInitList->setType(T);
492
Douglas Gregor5741efb2009-03-01 17:12:46 +0000493 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000494 // range corresponds with the end of the last initializer it used.
495 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000496 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
498 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
499 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000500}
501
Anders Carlsson6cabf312010-01-23 23:23:01 +0000502void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000503 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 unsigned &Index,
505 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000506 unsigned &StructuredIndex,
507 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000508 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 SyntacticToSemantic[IList] = StructuredList;
510 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000511 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
512 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000513 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000514 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000515 if (hadError)
516 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000517
Eli Friedman85f54972008-05-25 13:22:35 +0000518 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000519 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000520 if (StructuredIndex == 1 &&
521 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000522 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000523 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000524 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000525 hadError = true;
526 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000527 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000528 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000529 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000530 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000531 // Don't complain for incomplete types, since we'll get an error
532 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000533 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000534 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000535 CurrentObjectType->isArrayType()? 0 :
536 CurrentObjectType->isVectorType()? 1 :
537 CurrentObjectType->isScalarType()? 2 :
538 CurrentObjectType->isUnionType()? 3 :
539 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000540
541 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000542 if (SemaRef.getLangOptions().CPlusPlus) {
543 DK = diag::err_excess_initializers;
544 hadError = true;
545 }
Nate Begeman425038c2009-07-07 21:53:06 +0000546 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
547 DK = diag::err_excess_initializers;
548 hadError = true;
549 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000550
Chris Lattnerb0912a52009-02-24 22:50:46 +0000551 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000552 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000553 }
554 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000555
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000556 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000557 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000558 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000559 << CodeModificationHint::CreateRemoval(IList->getLocStart())
560 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000561}
562
Anders Carlsson6cabf312010-01-23 23:23:01 +0000563void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000564 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000565 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000566 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000567 unsigned &Index,
568 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000569 unsigned &StructuredIndex,
570 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000571 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000572 CheckScalarType(Entity, IList, DeclType, Index,
573 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000574 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000575 CheckVectorType(Entity, IList, DeclType, Index,
576 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000577 } else if (DeclType->isAggregateType()) {
578 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000579 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000580 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000581 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000582 StructuredList, StructuredIndex,
583 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000584 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000585 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000586 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000587 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000588 CheckArrayType(Entity, IList, DeclType, Zero,
589 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000590 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000591 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000593 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
594 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000596 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000597 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000598 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000599 } else if (DeclType->isRecordType()) {
600 // C++ [dcl.init]p14:
601 // [...] If the class is an aggregate (8.5.1), and the initializer
602 // is a brace-enclosed list, see 8.5.1.
603 //
604 // Note: 8.5.1 is handled below; here, we diagnose the case where
605 // we have an initializer list and a destination type that is not
606 // an aggregate.
607 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000609 << DeclType << IList->getSourceRange();
610 hadError = true;
611 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000612 CheckReferenceType(Entity, IList, DeclType, Index,
613 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000614 } else {
615 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000616 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000617 assert(0 && "Unsupported initializer type");
618 }
619}
620
Anders Carlsson6cabf312010-01-23 23:23:01 +0000621void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000622 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000623 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
626 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000627 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000628 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
629 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000630 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000631 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000632 = getStructuredSubobjectInit(IList, Index, ElemType,
633 StructuredList, StructuredIndex,
634 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000635 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000636 newStructuredList, newStructuredIndex);
637 ++StructuredIndex;
638 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000639 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
640 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000641 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000642 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000643 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000644 CheckScalarType(Entity, IList, ElemType, Index,
645 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000646 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000647 CheckReferenceType(Entity, IList, ElemType, Index,
648 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000649 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000650 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000651 // C++ [dcl.init.aggr]p12:
652 // All implicit type conversions (clause 4) are considered when
653 // initializing the aggregate member with an ini- tializer from
654 // an initializer-list. If the initializer can initialize a
655 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000656
Anders Carlsson0bd52402010-01-24 00:19:41 +0000657 // FIXME: Better EqualLoc?
658 InitializationKind Kind =
659 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
660 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
661
662 if (Seq) {
663 Sema::OwningExprResult Result =
664 Seq.Perform(SemaRef, Entity, Kind,
665 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
666 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000667 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000668
669 UpdateStructuredListElement(StructuredList, StructuredIndex,
670 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000671 ++Index;
672 return;
673 }
674
675 // Fall through for subaggregate initialization
676 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000677 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000678 //
679 // The initializer for a structure or union object that has
680 // automatic storage duration shall be either an initializer
681 // list as described below, or a single expression that has
682 // compatible structure or union type. In the latter case, the
683 // initial value of the object, including unnamed members, is
684 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000685 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000686 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000687 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
688 ++Index;
689 return;
690 }
691
692 // Fall through for subaggregate initialization
693 }
694
695 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000696 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000697 // [...] Otherwise, if the member is itself a non-empty
698 // subaggregate, brace elision is assumed and the initializer is
699 // considered for the initialization of the first member of
700 // the subaggregate.
701 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000702 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 StructuredIndex);
704 ++StructuredIndex;
705 } else {
706 // We cannot initialize this element, so let
707 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000708 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 hadError = true;
710 ++Index;
711 ++StructuredIndex;
712 }
713 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000714}
715
Anders Carlsson6cabf312010-01-23 23:23:01 +0000716void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000717 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000718 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000719 InitListExpr *StructuredList,
720 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000721 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000722 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000723 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000724 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000725 diag::err_many_braces_around_scalar_init)
726 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000727 hadError = true;
728 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000729 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000730 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000731 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000732 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000733 diag::err_designator_for_scalar_init)
734 << DeclType << expr->getSourceRange();
735 hadError = true;
736 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000737 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000738 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000739 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000740
Anders Carlsson26d05642010-01-23 18:35:41 +0000741 Sema::OwningExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000742 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
743 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000744
745 Expr *ResultExpr;
746
747 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000748 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000749 else {
750 ResultExpr = Result.takeAs<Expr>();
751
752 if (ResultExpr != expr) {
753 // The type was promoted, update initializer list.
754 IList->setInit(Index, ResultExpr);
755 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000756 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000757 if (hadError)
758 ++StructuredIndex;
759 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000760 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000761 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000762 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000763 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000764 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000766 ++Index;
767 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000768 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000769 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000770}
771
Anders Carlsson6cabf312010-01-23 23:23:01 +0000772void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
773 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000774 unsigned &Index,
775 InitListExpr *StructuredList,
776 unsigned &StructuredIndex) {
777 if (Index < IList->getNumInits()) {
778 Expr *expr = IList->getInit(Index);
779 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000780 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000781 << DeclType << IList->getSourceRange();
782 hadError = true;
783 ++Index;
784 ++StructuredIndex;
785 return;
Mike Stump11289f42009-09-09 15:08:12 +0000786 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000787
788 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000789 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000790 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000791 /*SuppressUserConversions=*/false,
792 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000793 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000794 hadError = true;
795 else if (savExpr != expr) {
796 // The type was promoted, update initializer list.
797 IList->setInit(Index, expr);
798 }
799 if (hadError)
800 ++StructuredIndex;
801 else
802 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
803 ++Index;
804 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000805 // FIXME: It would be wonderful if we could point at the actual member. In
806 // general, it would be useful to pass location information down the stack,
807 // so that we know the location (or decl) of the "current object" being
808 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000809 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000810 diag::err_init_reference_member_uninitialized)
811 << DeclType
812 << IList->getSourceRange();
813 hadError = true;
814 ++Index;
815 ++StructuredIndex;
816 return;
817 }
818}
819
Anders Carlsson6cabf312010-01-23 23:23:01 +0000820void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000821 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000822 unsigned &Index,
823 InitListExpr *StructuredList,
824 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000825 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000826 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000827 unsigned maxElements = VT->getNumElements();
828 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000829 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000830
Nate Begeman5ec4b312009-08-10 23:49:36 +0000831 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000832 InitializedEntity ElementEntity =
833 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000834
Anders Carlsson6cabf312010-01-23 23:23:01 +0000835 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
836 // Don't attempt to go past the end of the init list
837 if (Index >= IList->getNumInits())
838 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000839
Anders Carlsson6cabf312010-01-23 23:23:01 +0000840 ElementEntity.setElementIndex(Index);
841 CheckSubElementType(ElementEntity, IList, elementType, Index,
842 StructuredList, StructuredIndex);
843 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000844 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000845 InitializedEntity ElementEntity =
846 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
847
Nate Begeman5ec4b312009-08-10 23:49:36 +0000848 // OpenCL initializers allows vectors to be constructed from vectors.
849 for (unsigned i = 0; i < maxElements; ++i) {
850 // Don't attempt to go past the end of the init list
851 if (Index >= IList->getNumInits())
852 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000853
854 ElementEntity.setElementIndex(Index);
855
Nate Begeman5ec4b312009-08-10 23:49:36 +0000856 QualType IType = IList->getInit(Index)->getType();
857 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000858 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000859 StructuredList, StructuredIndex);
860 ++numEltsInit;
861 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000862 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000863 unsigned numIElts = IVT->getNumElements();
864 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
865 numIElts);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000866 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000867 StructuredList, StructuredIndex);
868 numEltsInit += numIElts;
869 }
870 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000871 }
Mike Stump11289f42009-09-09 15:08:12 +0000872
Nate Begeman5ec4b312009-08-10 23:49:36 +0000873 // OpenCL & AltiVec require all elements to be initialized.
874 if (numEltsInit != maxElements)
875 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
876 SemaRef.Diag(IList->getSourceRange().getBegin(),
877 diag::err_vector_incorrect_num_initializers)
878 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000879 }
880}
881
Anders Carlsson6cabf312010-01-23 23:23:01 +0000882void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000883 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000884 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000885 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000886 unsigned &Index,
887 InitListExpr *StructuredList,
888 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000889 // Check for the special-case of initializing an array with a string.
890 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000891 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
892 SemaRef.Context)) {
893 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000894 // We place the string literal directly into the resulting
895 // initializer list. This is the only place where the structure
896 // of the structured initializer list doesn't match exactly,
897 // because doing so would involve allocating one character
898 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000899 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000900 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000901 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000902 return;
903 }
904 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000905 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000906 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000907 // Check for VLAs; in standard C it would be possible to check this
908 // earlier, but I don't know where clang accepts VLAs (gcc accepts
909 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000910 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000911 diag::err_variable_object_no_init)
912 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000913 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000914 ++Index;
915 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000916 return;
917 }
918
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000919 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000920 llvm::APSInt maxElements(elementIndex.getBitWidth(),
921 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000922 bool maxElementsKnown = false;
923 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000924 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000925 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000926 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000927 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000928 maxElementsKnown = true;
929 }
930
Chris Lattnerb0912a52009-02-24 22:50:46 +0000931 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000932 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000933 while (Index < IList->getNumInits()) {
934 Expr *Init = IList->getInit(Index);
935 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000936 // If we're not the subobject that matches up with the '{' for
937 // the designator, we shouldn't be handling the
938 // designator. Return immediately.
939 if (!SubobjectIsDesignatorContext)
940 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000941
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000942 // Handle this designated initializer. elementIndex will be
943 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000944 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000945 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000946 StructuredList, StructuredIndex, true,
947 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000948 hadError = true;
949 continue;
950 }
951
Douglas Gregor033d1252009-01-23 16:54:12 +0000952 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
953 maxElements.extend(elementIndex.getBitWidth());
954 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
955 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000956 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000957
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000958 // If the array is of incomplete type, keep track of the number of
959 // elements in the initializer.
960 if (!maxElementsKnown && elementIndex > maxElements)
961 maxElements = elementIndex;
962
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000963 continue;
964 }
965
966 // If we know the maximum number of elements, and we've already
967 // hit it, stop consuming elements in the initializer list.
968 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000969 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000970
Anders Carlsson6cabf312010-01-23 23:23:01 +0000971 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000972 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000973 Entity);
974 // Check this element.
975 CheckSubElementType(ElementEntity, IList, elementType, Index,
976 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000977 ++elementIndex;
978
979 // If the array is of incomplete type, keep track of the number of
980 // elements in the initializer.
981 if (!maxElementsKnown && elementIndex > maxElements)
982 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000983 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000984 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000985 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000986 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000987 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000988 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000989 // Sizing an array implicitly to zero is not allowed by ISO C,
990 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000991 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000992 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +0000993 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000994
Mike Stump11289f42009-09-09 15:08:12 +0000995 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000996 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +0000997 }
998}
999
Anders Carlsson6cabf312010-01-23 23:23:01 +00001000void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001001 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001002 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001003 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001004 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001005 unsigned &Index,
1006 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001007 unsigned &StructuredIndex,
1008 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001009 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001010
Eli Friedman23a9e312008-05-19 19:16:24 +00001011 // If the record is invalid, some of it's members are invalid. To avoid
1012 // confusion, we forgo checking the intializer for the entire record.
1013 if (structDecl->isInvalidDecl()) {
1014 hadError = true;
1015 return;
Mike Stump11289f42009-09-09 15:08:12 +00001016 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001017
1018 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1019 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001020 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001021 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001022 Field != FieldEnd; ++Field) {
1023 if (Field->getDeclName()) {
1024 StructuredList->setInitializedFieldInUnion(*Field);
1025 break;
1026 }
1027 }
1028 return;
1029 }
1030
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001031 // If structDecl is a forward declaration, this loop won't do
1032 // anything except look at designated initializers; That's okay,
1033 // because an error should get printed out elsewhere. It might be
1034 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001035 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001036 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001037 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001038 while (Index < IList->getNumInits()) {
1039 Expr *Init = IList->getInit(Index);
1040
1041 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001042 // If we're not the subobject that matches up with the '{' for
1043 // the designator, we shouldn't be handling the
1044 // designator. Return immediately.
1045 if (!SubobjectIsDesignatorContext)
1046 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001047
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001048 // Handle this designated initializer. Field will be updated to
1049 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001050 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001051 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001052 StructuredList, StructuredIndex,
1053 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001054 hadError = true;
1055
Douglas Gregora9add4e2009-02-12 19:00:39 +00001056 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001057 continue;
1058 }
1059
1060 if (Field == FieldEnd) {
1061 // We've run out of fields. We're done.
1062 break;
1063 }
1064
Douglas Gregora9add4e2009-02-12 19:00:39 +00001065 // We've already initialized a member of a union. We're done.
1066 if (InitializedSomething && DeclType->isUnionType())
1067 break;
1068
Douglas Gregor91f84212008-12-11 16:49:14 +00001069 // If we've hit the flexible array member at the end, we're done.
1070 if (Field->getType()->isIncompleteArrayType())
1071 break;
1072
Douglas Gregor51695702009-01-29 16:53:55 +00001073 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001074 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001075 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001076 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001077 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001078
Anders Carlsson6cabf312010-01-23 23:23:01 +00001079 InitializedEntity MemberEntity =
1080 InitializedEntity::InitializeMember(*Field, &Entity);
1081 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1082 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001083 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001084
1085 if (DeclType->isUnionType()) {
1086 // Initialize the first field within the union.
1087 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001088 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001089
1090 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001091 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001092
Mike Stump11289f42009-09-09 15:08:12 +00001093 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001094 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001095 return;
1096
1097 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001098 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001099 (!isa<InitListExpr>(IList->getInit(Index)) ||
1100 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001101 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001102 diag::err_flexible_array_init_nonempty)
1103 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001104 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001105 << *Field;
1106 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001107 ++Index;
1108 return;
1109 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001110 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001111 diag::ext_flexible_array_init)
1112 << IList->getInit(Index)->getSourceRange().getBegin();
1113 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1114 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001115 }
1116
Anders Carlsson6cabf312010-01-23 23:23:01 +00001117 InitializedEntity MemberEntity =
1118 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001119
Anders Carlsson6cabf312010-01-23 23:23:01 +00001120 if (isa<InitListExpr>(IList->getInit(Index)))
1121 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1122 StructuredList, StructuredIndex);
1123 else
1124 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001125 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001126}
Steve Narofff8ecff22008-05-01 22:18:59 +00001127
Douglas Gregord5846a12009-04-15 06:41:24 +00001128/// \brief Expand a field designator that refers to a member of an
1129/// anonymous struct or union into a series of field designators that
1130/// refers to the field within the appropriate subobject.
1131///
1132/// Field/FieldIndex will be updated to point to the (new)
1133/// currently-designated field.
1134static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001135 DesignatedInitExpr *DIE,
1136 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001137 FieldDecl *Field,
1138 RecordDecl::field_iterator &FieldIter,
1139 unsigned &FieldIndex) {
1140 typedef DesignatedInitExpr::Designator Designator;
1141
1142 // Build the path from the current object to the member of the
1143 // anonymous struct/union (backwards).
1144 llvm::SmallVector<FieldDecl *, 4> Path;
1145 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregord5846a12009-04-15 06:41:24 +00001147 // Build the replacement designators.
1148 llvm::SmallVector<Designator, 4> Replacements;
1149 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1150 FI = Path.rbegin(), FIEnd = Path.rend();
1151 FI != FIEnd; ++FI) {
1152 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001153 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001154 DIE->getDesignator(DesigIdx)->getDotLoc(),
1155 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1156 else
1157 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1158 SourceLocation()));
1159 Replacements.back().setField(*FI);
1160 }
1161
1162 // Expand the current designator into the set of replacement
1163 // designators, so we have a full subobject path down to where the
1164 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001165 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001166 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001167
Douglas Gregord5846a12009-04-15 06:41:24 +00001168 // Update FieldIter/FieldIndex;
1169 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001170 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001171 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001172 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001173 FieldIter != FEnd; ++FieldIter) {
1174 if (FieldIter->isUnnamedBitfield())
1175 continue;
1176
1177 if (*FieldIter == Path.back())
1178 return;
1179
1180 ++FieldIndex;
1181 }
1182
1183 assert(false && "Unable to find anonymous struct/union field");
1184}
1185
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001186/// @brief Check the well-formedness of a C99 designated initializer.
1187///
1188/// Determines whether the designated initializer @p DIE, which
1189/// resides at the given @p Index within the initializer list @p
1190/// IList, is well-formed for a current object of type @p DeclType
1191/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001192/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001193/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001194///
1195/// @param IList The initializer list in which this designated
1196/// initializer occurs.
1197///
Douglas Gregora5324162009-04-15 04:56:10 +00001198/// @param DIE The designated initializer expression.
1199///
1200/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001201///
1202/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1203/// into which the designation in @p DIE should refer.
1204///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001205/// @param NextField If non-NULL and the first designator in @p DIE is
1206/// a field, this will be set to the field declaration corresponding
1207/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001208///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001209/// @param NextElementIndex If non-NULL and the first designator in @p
1210/// DIE is an array designator or GNU array-range designator, this
1211/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001212///
1213/// @param Index Index into @p IList where the designated initializer
1214/// @p DIE occurs.
1215///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001216/// @param StructuredList The initializer list expression that
1217/// describes all of the subobject initializers in the order they'll
1218/// actually be initialized.
1219///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001220/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001221bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001222InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001223 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001224 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001225 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001226 QualType &CurrentObjectType,
1227 RecordDecl::field_iterator *NextField,
1228 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001229 unsigned &Index,
1230 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001231 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001232 bool FinishSubobjectInit,
1233 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001234 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001235 // Check the actual initialization for the designated object type.
1236 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001237
1238 // Temporarily remove the designator expression from the
1239 // initializer list that the child calls see, so that we don't try
1240 // to re-process the designator.
1241 unsigned OldIndex = Index;
1242 IList->setInit(OldIndex, DIE->getInit());
1243
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001244 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001245 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001246
1247 // Restore the designated initializer expression in the syntactic
1248 // form of the initializer list.
1249 if (IList->getInit(OldIndex) != DIE->getInit())
1250 DIE->setInit(IList->getInit(OldIndex));
1251 IList->setInit(OldIndex, DIE);
1252
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001253 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001254 }
1255
Douglas Gregora5324162009-04-15 04:56:10 +00001256 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001257 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001258 "Need a non-designated initializer list to start from");
1259
Douglas Gregora5324162009-04-15 04:56:10 +00001260 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001261 // Determine the structural initializer list that corresponds to the
1262 // current subobject.
1263 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001264 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001265 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001266 SourceRange(D->getStartLocation(),
1267 DIE->getSourceRange().getEnd()));
1268 assert(StructuredList && "Expected a structured initializer list");
1269
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001270 if (D->isFieldDesignator()) {
1271 // C99 6.7.8p7:
1272 //
1273 // If a designator has the form
1274 //
1275 // . identifier
1276 //
1277 // then the current object (defined below) shall have
1278 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001279 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001280 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001281 if (!RT) {
1282 SourceLocation Loc = D->getDotLoc();
1283 if (Loc.isInvalid())
1284 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001285 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1286 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001287 ++Index;
1288 return true;
1289 }
1290
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001291 // Note: we perform a linear search of the fields here, despite
1292 // the fact that we have a faster lookup method, because we always
1293 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001294 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001295 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001296 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001297 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001298 Field = RT->getDecl()->field_begin(),
1299 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001300 for (; Field != FieldEnd; ++Field) {
1301 if (Field->isUnnamedBitfield())
1302 continue;
1303
Douglas Gregord5846a12009-04-15 06:41:24 +00001304 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001305 break;
1306
1307 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001308 }
1309
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001310 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001311 // There was no normal field in the struct with the designated
1312 // name. Perform another lookup for this name, which may find
1313 // something that we can't designate (e.g., a member function),
1314 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001315 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001316 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001317 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001318 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001319 // Name lookup didn't find anything. Determine whether this
1320 // was a typo for another field name.
1321 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1322 Sema::LookupMemberName);
1323 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1324 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1325 ReplacementField->getDeclContext()->getLookupContext()
1326 ->Equals(RT->getDecl())) {
1327 SemaRef.Diag(D->getFieldLoc(),
1328 diag::err_field_designator_unknown_suggest)
1329 << FieldName << CurrentObjectType << R.getLookupName()
1330 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1331 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001332 SemaRef.Diag(ReplacementField->getLocation(),
1333 diag::note_previous_decl)
1334 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001335 } else {
1336 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1337 << FieldName << CurrentObjectType;
1338 ++Index;
1339 return true;
1340 }
1341 } else if (!KnownField) {
1342 // Determine whether we found a field at all.
1343 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1344 }
1345
1346 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001348 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001349 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001350 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001351 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001352 ++Index;
1353 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001354 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001355
1356 if (!KnownField &&
1357 cast<RecordDecl>((ReplacementField)->getDeclContext())
1358 ->isAnonymousStructOrUnion()) {
1359 // Handle an field designator that refers to a member of an
1360 // anonymous struct or union.
1361 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1362 ReplacementField,
1363 Field, FieldIndex);
1364 D = DIE->getDesignator(DesigIdx);
1365 } else if (!KnownField) {
1366 // The replacement field comes from typo correction; find it
1367 // in the list of fields.
1368 FieldIndex = 0;
1369 Field = RT->getDecl()->field_begin();
1370 for (; Field != FieldEnd; ++Field) {
1371 if (Field->isUnnamedBitfield())
1372 continue;
1373
1374 if (ReplacementField == *Field ||
1375 Field->getIdentifier() == ReplacementField->getIdentifier())
1376 break;
1377
1378 ++FieldIndex;
1379 }
1380 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001381 } else if (!KnownField &&
1382 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001383 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001384 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1385 Field, FieldIndex);
1386 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001388
1389 // All of the fields of a union are located at the same place in
1390 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001391 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001392 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001393 StructuredList->setInitializedFieldInUnion(*Field);
1394 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001396 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001397 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001398
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 // Make sure that our non-designated initializer list has space
1400 // for a subobject corresponding to this field.
1401 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001402 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001403
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001404 // This designator names a flexible array member.
1405 if (Field->getType()->isIncompleteArrayType()) {
1406 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001407 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001408 // We can't designate an object within the flexible array
1409 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001410 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001411 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001412 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001413 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001414 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001415 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001416 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001417 << *Field;
1418 Invalid = true;
1419 }
1420
1421 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1422 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001423 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001424 diag::err_flexible_array_init_needs_braces)
1425 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001426 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001427 << *Field;
1428 Invalid = true;
1429 }
1430
1431 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001432 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001433 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001434 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001435 diag::err_flexible_array_init_nonempty)
1436 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001437 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001438 << *Field;
1439 Invalid = true;
1440 }
1441
1442 if (Invalid) {
1443 ++Index;
1444 return true;
1445 }
1446
1447 // Initialize the array.
1448 bool prevHadError = hadError;
1449 unsigned newStructuredIndex = FieldIndex;
1450 unsigned OldIndex = Index;
1451 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001452
1453 InitializedEntity MemberEntity =
1454 InitializedEntity::InitializeMember(*Field, &Entity);
1455 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001457
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001458 IList->setInit(OldIndex, DIE);
1459 if (hadError && !prevHadError) {
1460 ++Field;
1461 ++FieldIndex;
1462 if (NextField)
1463 *NextField = Field;
1464 StructuredIndex = FieldIndex;
1465 return true;
1466 }
1467 } else {
1468 // Recurse to check later designated subobjects.
1469 QualType FieldType = (*Field)->getType();
1470 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001471
1472 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001473 InitializedEntity::InitializeMember(*Field, &Entity);
1474 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001475 FieldType, 0, 0, Index,
1476 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001477 true, false))
1478 return true;
1479 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001480
1481 // Find the position of the next field to be initialized in this
1482 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001483 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001484 ++FieldIndex;
Douglas Gregord7fb85e2009-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 Gregor347f7ea2009-01-28 21:54:33 +00001491 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001492 return false;
1493 }
1494
Douglas Gregor17bd0942009-01-28 23:36:17 +00001495 if (!FinishSubobjectInit)
1496 return false;
1497
Douglas Gregord5846a12009-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 Gregord7fb85e2009-01-22 23:26:18 +00001502 // Check the remaining fields within this class/struct/union subobject.
1503 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001504
Anders Carlsson6cabf312010-01-23 23:23:01 +00001505 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001506 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001507 return hadError && !prevHadError;
1508 }
1509
1510 // C99 6.7.8p6:
1511 //
1512 // If a designator has the form
1513 //
1514 // [ constant-expression ]
1515 //
1516 // then the current object (defined below) shall have array
1517 // type and the expression shall be an integer constant
1518 // expression. If the array is of unknown size, any
1519 // nonnegative value is valid.
1520 //
1521 // Additionally, cope with the GNU extension that permits
1522 // designators of the form
1523 //
1524 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001525 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001527 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001528 << CurrentObjectType;
1529 ++Index;
1530 return true;
1531 }
1532
1533 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001534 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1535 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001536 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001537 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001538 DesignatedEndIndex = DesignatedStartIndex;
1539 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001540 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001541
Mike Stump11289f42009-09-09 15:08:12 +00001542
1543 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001544 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001545 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001546 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001547 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001548
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001549 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001550 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001551 }
1552
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001553 if (isa<ConstantArrayType>(AT)) {
1554 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001555 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1556 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1557 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1558 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1559 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001560 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001561 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001562 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001563 << IndexExpr->getSourceRange();
1564 ++Index;
1565 return true;
1566 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001567 } else {
1568 // Make sure the bit-widths and signedness match.
1569 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1570 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001571 else if (DesignatedStartIndex.getBitWidth() <
1572 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001573 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1574 DesignatedStartIndex.setIsUnsigned(true);
1575 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001578 // Make sure that our non-designated initializer list has space
1579 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001580 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001581 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001582 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001583
Douglas Gregor17bd0942009-01-28 23:36:17 +00001584 // Repeatedly perform subobject initializations in the range
1585 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001586
Douglas Gregor17bd0942009-01-28 23:36:17 +00001587 // Move to the next designator
1588 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1589 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001590
1591 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001592 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001593
Douglas Gregor17bd0942009-01-28 23:36:17 +00001594 while (DesignatedStartIndex <= DesignatedEndIndex) {
1595 // Recurse to check later designated subobjects.
1596 QualType ElementType = AT->getElementType();
1597 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001598
1599 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001600 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001601 ElementType, 0, 0, Index,
1602 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001603 (DesignatedStartIndex == DesignatedEndIndex),
1604 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001605 return true;
1606
1607 // Move to the next index in the array that we'll be initializing.
1608 ++DesignatedStartIndex;
1609 ElementIndex = DesignatedStartIndex.getZExtValue();
1610 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001611
1612 // If this the first designator, our caller will continue checking
1613 // the rest of this array subobject.
1614 if (IsFirstDesignator) {
1615 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001616 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001617 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001618 return false;
1619 }
Mike Stump11289f42009-09-09 15:08:12 +00001620
Douglas Gregor17bd0942009-01-28 23:36:17 +00001621 if (!FinishSubobjectInit)
1622 return false;
1623
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001624 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001625 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001626 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001627 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001628 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001629 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001630}
1631
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001632// Get the structured initializer list for a subobject of type
1633// @p CurrentObjectType.
1634InitListExpr *
1635InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1636 QualType CurrentObjectType,
1637 InitListExpr *StructuredList,
1638 unsigned StructuredIndex,
1639 SourceRange InitRange) {
1640 Expr *ExistingInit = 0;
1641 if (!StructuredList)
1642 ExistingInit = SyntacticToSemantic[IList];
1643 else if (StructuredIndex < StructuredList->getNumInits())
1644 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001645
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001646 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1647 return Result;
1648
1649 if (ExistingInit) {
1650 // We are creating an initializer list that initializes the
1651 // subobjects of the current object, but there was already an
1652 // initialization that completely initialized the current
1653 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001654 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001655 // struct X { int a, b; };
1656 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001657 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001658 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1659 // designated initializer re-initializes the whole
1660 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001661 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001662 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001664 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001665 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001666 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 << ExistingInit->getSourceRange();
1668 }
1669
Mike Stump11289f42009-09-09 15:08:12 +00001670 InitListExpr *Result
1671 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001672 InitRange.getEnd());
1673
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 Result->setType(CurrentObjectType);
1675
Douglas Gregor6d00c992009-03-20 23:58:33 +00001676 // Pre-allocate storage for the structured initializer list.
1677 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001678 unsigned NumInits = 0;
1679 if (!StructuredList)
1680 NumInits = IList->getNumInits();
1681 else if (Index < IList->getNumInits()) {
1682 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1683 NumInits = SubList->getNumInits();
1684 }
1685
Mike Stump11289f42009-09-09 15:08:12 +00001686 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001687 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1688 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1689 NumElements = CAType->getSize().getZExtValue();
1690 // Simple heuristic so that we don't allocate a very large
1691 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001692 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001693 NumElements = 0;
1694 }
John McCall9dd450b2009-09-21 23:43:11 +00001695 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001696 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001697 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001698 RecordDecl *RDecl = RType->getDecl();
1699 if (RDecl->isUnion())
1700 NumElements = 1;
1701 else
Mike Stump11289f42009-09-09 15:08:12 +00001702 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001703 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001704 }
1705
Douglas Gregor221c9a52009-03-21 18:13:52 +00001706 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001707 NumElements = IList->getNumInits();
1708
1709 Result->reserveInits(NumElements);
1710
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 // Link this new initializer list into the structured initializer
1712 // lists.
1713 if (StructuredList)
1714 StructuredList->updateInit(StructuredIndex, Result);
1715 else {
1716 Result->setSyntacticForm(IList);
1717 SyntacticToSemantic[IList] = Result;
1718 }
1719
1720 return Result;
1721}
1722
1723/// Update the initializer at index @p StructuredIndex within the
1724/// structured initializer list to the value @p expr.
1725void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1726 unsigned &StructuredIndex,
1727 Expr *expr) {
1728 // No structured initializer list to update
1729 if (!StructuredList)
1730 return;
1731
1732 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1733 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001734 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001735 diag::warn_initializer_overrides)
1736 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001737 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001738 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001739 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 << PrevInit->getSourceRange();
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 ++StructuredIndex;
1744}
1745
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001746/// Check that the given Index expression is a valid array designator
1747/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001748/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001749/// and produces a reasonable diagnostic if there is a
1750/// failure. Returns true if there was an error, false otherwise. If
1751/// everything went okay, Value will receive the value of the constant
1752/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001753static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001754CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001755 SourceLocation Loc = Index->getSourceRange().getBegin();
1756
1757 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001758 if (S.VerifyIntegerConstantExpression(Index, &Value))
1759 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001760
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001761 if (Value.isSigned() && Value.isNegative())
1762 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001763 << Value.toString(10) << Index->getSourceRange();
1764
Douglas Gregor51650d32009-01-23 21:04:18 +00001765 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001766 return false;
1767}
1768
1769Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1770 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001771 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001772 OwningExprResult Init) {
1773 typedef DesignatedInitExpr::Designator ASTDesignator;
1774
1775 bool Invalid = false;
1776 llvm::SmallVector<ASTDesignator, 32> Designators;
1777 llvm::SmallVector<Expr *, 32> InitExpressions;
1778
1779 // Build designators and check array designator expressions.
1780 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1781 const Designator &D = Desig.getDesignator(Idx);
1782 switch (D.getKind()) {
1783 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001784 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001785 D.getFieldLoc()));
1786 break;
1787
1788 case Designator::ArrayDesignator: {
1789 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1790 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001791 if (!Index->isTypeDependent() &&
1792 !Index->isValueDependent() &&
1793 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001794 Invalid = true;
1795 else {
1796 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001797 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001798 D.getRBracketLoc()));
1799 InitExpressions.push_back(Index);
1800 }
1801 break;
1802 }
1803
1804 case Designator::ArrayRangeDesignator: {
1805 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1806 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1807 llvm::APSInt StartValue;
1808 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001809 bool StartDependent = StartIndex->isTypeDependent() ||
1810 StartIndex->isValueDependent();
1811 bool EndDependent = EndIndex->isTypeDependent() ||
1812 EndIndex->isValueDependent();
1813 if ((!StartDependent &&
1814 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1815 (!EndDependent &&
1816 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001817 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001818 else {
1819 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001820 if (StartDependent || EndDependent) {
1821 // Nothing to compute.
1822 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001823 EndValue.extend(StartValue.getBitWidth());
1824 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1825 StartValue.extend(EndValue.getBitWidth());
1826
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001827 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001828 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001829 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001830 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1831 Invalid = true;
1832 } else {
1833 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001834 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001835 D.getEllipsisLoc(),
1836 D.getRBracketLoc()));
1837 InitExpressions.push_back(StartIndex);
1838 InitExpressions.push_back(EndIndex);
1839 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001840 }
1841 break;
1842 }
1843 }
1844 }
1845
1846 if (Invalid || Init.isInvalid())
1847 return ExprError();
1848
1849 // Clear out the expressions within the designation.
1850 Desig.ClearExprs(*this);
1851
1852 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001853 = DesignatedInitExpr::Create(Context,
1854 Designators.data(), Designators.size(),
1855 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001856 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001857 return Owned(DIE);
1858}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001859
Douglas Gregor723796a2009-12-16 06:35:08 +00001860bool Sema::CheckInitList(const InitializedEntity &Entity,
1861 InitListExpr *&InitList, QualType &DeclType) {
1862 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001863 if (!CheckInitList.HadError())
1864 InitList = CheckInitList.getFullyStructuredList();
1865
1866 return CheckInitList.HadError();
1867}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001868
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001869//===----------------------------------------------------------------------===//
1870// Initialization entity
1871//===----------------------------------------------------------------------===//
1872
Douglas Gregor723796a2009-12-16 06:35:08 +00001873InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1874 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001875 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001876{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001877 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1878 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001879 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001880 } else {
1881 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001882 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001883 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001884}
1885
1886InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1887 CXXBaseSpecifier *Base)
1888{
1889 InitializedEntity Result;
1890 Result.Kind = EK_Base;
1891 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001892 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001893 return Result;
1894}
1895
Douglas Gregor85dabae2009-12-16 01:38:02 +00001896DeclarationName InitializedEntity::getName() const {
1897 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001898 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001899 if (!VariableOrMember)
1900 return DeclarationName();
1901 // Fall through
1902
1903 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001904 case EK_Member:
1905 return VariableOrMember->getDeclName();
1906
1907 case EK_Result:
1908 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001909 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001910 case EK_Temporary:
1911 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001912 case EK_ArrayElement:
1913 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001914 return DeclarationName();
1915 }
1916
1917 // Silence GCC warning
1918 return DeclarationName();
1919}
1920
Douglas Gregora4b592a2009-12-19 03:01:41 +00001921DeclaratorDecl *InitializedEntity::getDecl() const {
1922 switch (getKind()) {
1923 case EK_Variable:
1924 case EK_Parameter:
1925 case EK_Member:
1926 return VariableOrMember;
1927
1928 case EK_Result:
1929 case EK_Exception:
1930 case EK_New:
1931 case EK_Temporary:
1932 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001933 case EK_ArrayElement:
1934 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001935 return 0;
1936 }
1937
1938 // Silence GCC warning
1939 return 0;
1940}
1941
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001942//===----------------------------------------------------------------------===//
1943// Initialization sequence
1944//===----------------------------------------------------------------------===//
1945
1946void InitializationSequence::Step::Destroy() {
1947 switch (Kind) {
1948 case SK_ResolveAddressOfOverloadedFunction:
1949 case SK_CastDerivedToBaseRValue:
1950 case SK_CastDerivedToBaseLValue:
1951 case SK_BindReference:
1952 case SK_BindReferenceToTemporary:
1953 case SK_UserConversion:
1954 case SK_QualificationConversionRValue:
1955 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001956 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001957 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001958 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001959 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001960 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001961 break;
1962
1963 case SK_ConversionSequence:
1964 delete ICS;
1965 }
1966}
1967
1968void InitializationSequence::AddAddressOverloadResolutionStep(
1969 FunctionDecl *Function) {
1970 Step S;
1971 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1972 S.Type = Function->getType();
1973 S.Function = Function;
1974 Steps.push_back(S);
1975}
1976
1977void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1978 bool IsLValue) {
1979 Step S;
1980 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1981 S.Type = BaseType;
1982 Steps.push_back(S);
1983}
1984
1985void InitializationSequence::AddReferenceBindingStep(QualType T,
1986 bool BindingTemporary) {
1987 Step S;
1988 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1989 S.Type = T;
1990 Steps.push_back(S);
1991}
1992
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001993void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1994 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001995 Step S;
1996 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001997 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001998 S.Function = Function;
1999 Steps.push_back(S);
2000}
2001
2002void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2003 bool IsLValue) {
2004 Step S;
2005 S.Kind = IsLValue? SK_QualificationConversionLValue
2006 : SK_QualificationConversionRValue;
2007 S.Type = Ty;
2008 Steps.push_back(S);
2009}
2010
2011void InitializationSequence::AddConversionSequenceStep(
2012 const ImplicitConversionSequence &ICS,
2013 QualType T) {
2014 Step S;
2015 S.Kind = SK_ConversionSequence;
2016 S.Type = T;
2017 S.ICS = new ImplicitConversionSequence(ICS);
2018 Steps.push_back(S);
2019}
2020
Douglas Gregor51e77d52009-12-10 17:56:55 +00002021void InitializationSequence::AddListInitializationStep(QualType T) {
2022 Step S;
2023 S.Kind = SK_ListInitialization;
2024 S.Type = T;
2025 Steps.push_back(S);
2026}
2027
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002028void
2029InitializationSequence::AddConstructorInitializationStep(
2030 CXXConstructorDecl *Constructor,
2031 QualType T) {
2032 Step S;
2033 S.Kind = SK_ConstructorInitialization;
2034 S.Type = T;
2035 S.Function = Constructor;
2036 Steps.push_back(S);
2037}
2038
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002039void InitializationSequence::AddZeroInitializationStep(QualType T) {
2040 Step S;
2041 S.Kind = SK_ZeroInitialization;
2042 S.Type = T;
2043 Steps.push_back(S);
2044}
2045
Douglas Gregore1314a62009-12-18 05:02:21 +00002046void InitializationSequence::AddCAssignmentStep(QualType T) {
2047 Step S;
2048 S.Kind = SK_CAssignment;
2049 S.Type = T;
2050 Steps.push_back(S);
2051}
2052
Eli Friedman78275202009-12-19 08:11:05 +00002053void InitializationSequence::AddStringInitStep(QualType T) {
2054 Step S;
2055 S.Kind = SK_StringInit;
2056 S.Type = T;
2057 Steps.push_back(S);
2058}
2059
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002060void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2061 OverloadingResult Result) {
2062 SequenceKind = FailedSequence;
2063 this->Failure = Failure;
2064 this->FailedOverloadResult = Result;
2065}
2066
2067//===----------------------------------------------------------------------===//
2068// Attempt initialization
2069//===----------------------------------------------------------------------===//
2070
2071/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002072static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002073 const InitializedEntity &Entity,
2074 const InitializationKind &Kind,
2075 InitListExpr *InitList,
2076 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002077 // FIXME: We only perform rudimentary checking of list
2078 // initializations at this point, then assume that any list
2079 // initialization of an array, aggregate, or scalar will be
2080 // well-formed. We we actually "perform" list initialization, we'll
2081 // do all of the necessary checking. C++0x initializer lists will
2082 // force us to perform more checking here.
2083 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2084
Douglas Gregor1b303932009-12-22 15:35:07 +00002085 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002086
2087 // C++ [dcl.init]p13:
2088 // If T is a scalar type, then a declaration of the form
2089 //
2090 // T x = { a };
2091 //
2092 // is equivalent to
2093 //
2094 // T x = a;
2095 if (DestType->isScalarType()) {
2096 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2097 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2098 return;
2099 }
2100
2101 // Assume scalar initialization from a single value works.
2102 } else if (DestType->isAggregateType()) {
2103 // Assume aggregate initialization works.
2104 } else if (DestType->isVectorType()) {
2105 // Assume vector initialization works.
2106 } else if (DestType->isReferenceType()) {
2107 // FIXME: C++0x defines behavior for this.
2108 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2109 return;
2110 } else if (DestType->isRecordType()) {
2111 // FIXME: C++0x defines behavior for this
2112 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2113 }
2114
2115 // Add a general "list initialization" step.
2116 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002117}
2118
2119/// \brief Try a reference initialization that involves calling a conversion
2120/// function.
2121///
2122/// FIXME: look intos DRs 656, 896
2123static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2124 const InitializedEntity &Entity,
2125 const InitializationKind &Kind,
2126 Expr *Initializer,
2127 bool AllowRValues,
2128 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002129 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002130 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2131 QualType T1 = cv1T1.getUnqualifiedType();
2132 QualType cv2T2 = Initializer->getType();
2133 QualType T2 = cv2T2.getUnqualifiedType();
2134
2135 bool DerivedToBase;
2136 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2137 T1, T2, DerivedToBase) &&
2138 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002139 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002140
2141 // Build the candidate set directly in the initialization sequence
2142 // structure, so that it will persist if we fail.
2143 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2144 CandidateSet.clear();
2145
2146 // Determine whether we are allowed to call explicit constructors or
2147 // explicit conversion operators.
2148 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2149
2150 const RecordType *T1RecordType = 0;
2151 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2152 // The type we're converting to is a class type. Enumerate its constructors
2153 // to see if there is a suitable conversion.
2154 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2155
2156 DeclarationName ConstructorName
2157 = S.Context.DeclarationNames.getCXXConstructorName(
2158 S.Context.getCanonicalType(T1).getUnqualifiedType());
2159 DeclContext::lookup_iterator Con, ConEnd;
2160 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2161 Con != ConEnd; ++Con) {
2162 // Find the constructor (which may be a template).
2163 CXXConstructorDecl *Constructor = 0;
2164 FunctionTemplateDecl *ConstructorTmpl
2165 = dyn_cast<FunctionTemplateDecl>(*Con);
2166 if (ConstructorTmpl)
2167 Constructor = cast<CXXConstructorDecl>(
2168 ConstructorTmpl->getTemplatedDecl());
2169 else
2170 Constructor = cast<CXXConstructorDecl>(*Con);
2171
2172 if (!Constructor->isInvalidDecl() &&
2173 Constructor->isConvertingConstructor(AllowExplicit)) {
2174 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002175 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2176 ConstructorTmpl->getAccess(),
2177 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002178 &Initializer, 1, CandidateSet);
2179 else
John McCallb89836b2010-01-26 01:37:31 +00002180 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2181 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002182 }
2183 }
2184 }
2185
2186 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2187 // The type we're converting from is a class type, enumerate its conversion
2188 // functions.
2189 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2190
2191 // Determine the type we are converting to. If we are allowed to
2192 // convert to an rvalue, take the type that the destination type
2193 // refers to.
2194 QualType ToType = AllowRValues? cv1T1 : DestType;
2195
John McCallad371252010-01-20 00:46:10 +00002196 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002197 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002198 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2199 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002200 NamedDecl *D = *I;
2201 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2202 if (isa<UsingShadowDecl>(D))
2203 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2204
2205 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2206 CXXConversionDecl *Conv;
2207 if (ConvTemplate)
2208 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2209 else
2210 Conv = cast<CXXConversionDecl>(*I);
2211
2212 // If the conversion function doesn't return a reference type,
2213 // it can't be considered for this conversion unless we're allowed to
2214 // consider rvalues.
2215 // FIXME: Do we need to make sure that we only consider conversion
2216 // candidates with reference-compatible results? That might be needed to
2217 // break recursion.
2218 if ((AllowExplicit || !Conv->isExplicit()) &&
2219 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2220 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00002221 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2222 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002223 ToType, CandidateSet);
2224 else
John McCallb89836b2010-01-26 01:37:31 +00002225 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2226 Initializer, cv1T1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002227 }
2228 }
2229 }
2230
2231 SourceLocation DeclLoc = Initializer->getLocStart();
2232
2233 // Perform overload resolution. If it fails, return the failed result.
2234 OverloadCandidateSet::iterator Best;
2235 if (OverloadingResult Result
2236 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2237 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002238
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002239 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002240
2241 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002242 if (isa<CXXConversionDecl>(Function))
2243 T2 = Function->getResultType();
2244 else
2245 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002246
2247 // Add the user-defined conversion step.
2248 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2249
2250 // Determine whether we need to perform derived-to-base or
2251 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002252 bool NewDerivedToBase = false;
2253 Sema::ReferenceCompareResult NewRefRelationship
2254 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2255 NewDerivedToBase);
2256 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2257 "Overload resolution picked a bad conversion function");
2258 (void)NewRefRelationship;
2259 if (NewDerivedToBase)
2260 Sequence.AddDerivedToBaseCastStep(
2261 S.Context.getQualifiedType(T1,
2262 T2.getNonReferenceType().getQualifiers()),
2263 /*isLValue=*/true);
2264
2265 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2266 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2267
2268 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2269 return OR_Success;
2270}
2271
2272/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2273static void TryReferenceInitialization(Sema &S,
2274 const InitializedEntity &Entity,
2275 const InitializationKind &Kind,
2276 Expr *Initializer,
2277 InitializationSequence &Sequence) {
2278 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2279
Douglas Gregor1b303932009-12-22 15:35:07 +00002280 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002281 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002282 Qualifiers T1Quals;
2283 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002284 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002285 Qualifiers T2Quals;
2286 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002287 SourceLocation DeclLoc = Initializer->getLocStart();
2288
2289 // If the initializer is the address of an overloaded function, try
2290 // to resolve the overloaded function. If all goes well, T2 is the
2291 // type of the resulting function.
2292 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2293 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2294 T1,
2295 false);
2296 if (!Fn) {
2297 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2298 return;
2299 }
2300
2301 Sequence.AddAddressOverloadResolutionStep(Fn);
2302 cv2T2 = Fn->getType();
2303 T2 = cv2T2.getUnqualifiedType();
2304 }
2305
2306 // FIXME: Rvalue references
2307 bool ForceRValue = false;
2308
2309 // Compute some basic properties of the types and the initializer.
2310 bool isLValueRef = DestType->isLValueReferenceType();
2311 bool isRValueRef = !isLValueRef;
2312 bool DerivedToBase = false;
2313 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2314 Initializer->isLvalue(S.Context);
2315 Sema::ReferenceCompareResult RefRelationship
2316 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2317
2318 // C++0x [dcl.init.ref]p5:
2319 // A reference to type "cv1 T1" is initialized by an expression of type
2320 // "cv2 T2" as follows:
2321 //
2322 // - If the reference is an lvalue reference and the initializer
2323 // expression
2324 OverloadingResult ConvOvlResult = OR_Success;
2325 if (isLValueRef) {
2326 if (InitLvalue == Expr::LV_Valid &&
2327 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2328 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2329 // reference-compatible with "cv2 T2," or
2330 //
2331 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2332 // bit-field when we're determining whether the reference initialization
2333 // can occur. This property will be checked by PerformInitialization.
2334 if (DerivedToBase)
2335 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002336 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002337 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002338 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002339 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2340 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2341 return;
2342 }
2343
2344 // - has a class type (i.e., T2 is a class type), where T1 is not
2345 // reference-related to T2, and can be implicitly converted to an
2346 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2347 // with "cv3 T3" (this conversion is selected by enumerating the
2348 // applicable conversion functions (13.3.1.6) and choosing the best
2349 // one through overload resolution (13.3)),
2350 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2351 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2352 Initializer,
2353 /*AllowRValues=*/false,
2354 Sequence);
2355 if (ConvOvlResult == OR_Success)
2356 return;
John McCall0d1da222010-01-12 00:44:57 +00002357 if (ConvOvlResult != OR_No_Viable_Function) {
2358 Sequence.SetOverloadFailure(
2359 InitializationSequence::FK_ReferenceInitOverloadFailed,
2360 ConvOvlResult);
2361 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002362 }
2363 }
2364
2365 // - Otherwise, the reference shall be an lvalue reference to a
2366 // non-volatile const type (i.e., cv1 shall be const), or the reference
2367 // shall be an rvalue reference and the initializer expression shall
2368 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002369 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002370 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2371 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2372 Sequence.SetOverloadFailure(
2373 InitializationSequence::FK_ReferenceInitOverloadFailed,
2374 ConvOvlResult);
2375 else if (isLValueRef)
2376 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2377 ? (RefRelationship == Sema::Ref_Related
2378 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2379 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2380 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2381 else
2382 Sequence.SetFailed(
2383 InitializationSequence::FK_RValueReferenceBindingToLValue);
2384
2385 return;
2386 }
2387
2388 // - If T1 and T2 are class types and
2389 if (T1->isRecordType() && T2->isRecordType()) {
2390 // - the initializer expression is an rvalue and "cv1 T1" is
2391 // reference-compatible with "cv2 T2", or
2392 if (InitLvalue != Expr::LV_Valid &&
2393 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2394 if (DerivedToBase)
2395 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002396 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002398 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2400 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2401 return;
2402 }
2403
2404 // - T1 is not reference-related to T2 and the initializer expression
2405 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2406 // conversion is selected by enumerating the applicable conversion
2407 // functions (13.3.1.6) and choosing the best one through overload
2408 // resolution (13.3)),
2409 if (RefRelationship == Sema::Ref_Incompatible) {
2410 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2411 Kind, Initializer,
2412 /*AllowRValues=*/true,
2413 Sequence);
2414 if (ConvOvlResult)
2415 Sequence.SetOverloadFailure(
2416 InitializationSequence::FK_ReferenceInitOverloadFailed,
2417 ConvOvlResult);
2418
2419 return;
2420 }
2421
2422 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2423 return;
2424 }
2425
2426 // - If the initializer expression is an rvalue, with T2 an array type,
2427 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2428 // is bound to the object represented by the rvalue (see 3.10).
2429 // FIXME: How can an array type be reference-compatible with anything?
2430 // Don't we mean the element types of T1 and T2?
2431
2432 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2433 // from the initializer expression using the rules for a non-reference
2434 // copy initialization (8.5). The reference is then bound to the
2435 // temporary. [...]
2436 // Determine whether we are allowed to call explicit constructors or
2437 // explicit conversion operators.
2438 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2439 ImplicitConversionSequence ICS
2440 = S.TryImplicitConversion(Initializer, cv1T1,
2441 /*SuppressUserConversions=*/false, AllowExplicit,
2442 /*ForceRValue=*/false,
2443 /*FIXME:InOverloadResolution=*/false,
2444 /*UserCast=*/Kind.isExplicitCast());
2445
John McCall0d1da222010-01-12 00:44:57 +00002446 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002447 // FIXME: Use the conversion function set stored in ICS to turn
2448 // this into an overloading ambiguity diagnostic. However, we need
2449 // to keep that set as an OverloadCandidateSet rather than as some
2450 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002451 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2452 Sequence.SetOverloadFailure(
2453 InitializationSequence::FK_ReferenceInitOverloadFailed,
2454 ConvOvlResult);
2455 else
2456 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002457 return;
2458 }
2459
2460 // [...] If T1 is reference-related to T2, cv1 must be the
2461 // same cv-qualification as, or greater cv-qualification
2462 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002463 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2464 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002465 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002466 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002467 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2468 return;
2469 }
2470
2471 // Perform the actual conversion.
2472 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2473 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2474 return;
2475}
2476
2477/// \brief Attempt character array initialization from a string literal
2478/// (C++ [dcl.init.string], C99 6.7.8).
2479static void TryStringLiteralInitialization(Sema &S,
2480 const InitializedEntity &Entity,
2481 const InitializationKind &Kind,
2482 Expr *Initializer,
2483 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002484 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002485 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002486}
2487
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2489/// enumerates the constructors of the initialized entity and performs overload
2490/// resolution to select the best.
2491static void TryConstructorInitialization(Sema &S,
2492 const InitializedEntity &Entity,
2493 const InitializationKind &Kind,
2494 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002495 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002496 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002497 if (Kind.getKind() == InitializationKind::IK_Copy)
2498 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2499 else
2500 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-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 Gregor1e7ffa72009-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 Gregor85dabae2009-12-16 01:38:02 +00002537 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002538 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002539 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2540 ConstructorTmpl->getAccess(),
2541 /*ExplicitArgs*/ 0,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002542 Args, NumArgs, CandidateSet);
2543 else
John McCallb89836b2010-01-26 01:37:31 +00002544 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2545 Args, NumArgs, CandidateSet);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002546 }
2547 }
2548
2549 SourceLocation DeclLoc = Kind.getLocation();
2550
2551 // Perform overload resolution. If it fails, return the failed result.
2552 OverloadCandidateSet::iterator Best;
2553 if (OverloadingResult Result
2554 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2555 Sequence.SetOverloadFailure(
2556 InitializationSequence::FK_ConstructorOverloadFailed,
2557 Result);
2558 return;
2559 }
2560
2561 // Add the constructor initialization step. Any cv-qualification conversion is
2562 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002563 if (Kind.getKind() == InitializationKind::IK_Copy) {
2564 Sequence.AddUserConversionStep(Best->Function, DestType);
2565 } else {
2566 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002567 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002568 DestType);
2569 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002570}
2571
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002572/// \brief Attempt value initialization (C++ [dcl.init]p7).
2573static void TryValueInitialization(Sema &S,
2574 const InitializedEntity &Entity,
2575 const InitializationKind &Kind,
2576 InitializationSequence &Sequence) {
2577 // C++ [dcl.init]p5:
2578 //
2579 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002580 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002581
2582 // -- if T is an array type, then each element is value-initialized;
2583 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2584 T = AT->getElementType();
2585
2586 if (const RecordType *RT = T->getAs<RecordType>()) {
2587 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2588 // -- if T is a class type (clause 9) with a user-declared
2589 // constructor (12.1), then the default constructor for T is
2590 // called (and the initialization is ill-formed if T has no
2591 // accessible default constructor);
2592 //
2593 // FIXME: we really want to refer to a single subobject of the array,
2594 // but Entity doesn't have a way to capture that (yet).
2595 if (ClassDecl->hasUserDeclaredConstructor())
2596 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2597
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002598 // -- if T is a (possibly cv-qualified) non-union class type
2599 // without a user-provided constructor, then the object is
2600 // zero-initialized and, if T’s implicitly-declared default
2601 // constructor is non-trivial, that constructor is called.
2602 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2603 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2604 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002605 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002606 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2607 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002608 }
2609 }
2610
Douglas Gregor1b303932009-12-22 15:35:07 +00002611 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002612 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2613}
2614
Douglas Gregor85dabae2009-12-16 01:38:02 +00002615/// \brief Attempt default initialization (C++ [dcl.init]p6).
2616static void TryDefaultInitialization(Sema &S,
2617 const InitializedEntity &Entity,
2618 const InitializationKind &Kind,
2619 InitializationSequence &Sequence) {
2620 assert(Kind.getKind() == InitializationKind::IK_Default);
2621
2622 // C++ [dcl.init]p6:
2623 // To default-initialize an object of type T means:
2624 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002625 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002626 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2627 DestType = Array->getElementType();
2628
2629 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2630 // constructor for T is called (and the initialization is ill-formed if
2631 // T has no accessible default constructor);
2632 if (DestType->isRecordType()) {
2633 // FIXME: If a program calls for the default initialization of an object of
2634 // a const-qualified type T, T shall be a class type with a user-provided
2635 // default constructor.
2636 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2637 Sequence);
2638 }
2639
2640 // - otherwise, no initialization is performed.
2641 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2642
2643 // If a program calls for the default initialization of an object of
2644 // a const-qualified type T, T shall be a class type with a user-provided
2645 // default constructor.
2646 if (DestType.isConstQualified())
2647 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2648}
2649
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002650/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2651/// which enumerates all conversion functions and performs overload resolution
2652/// to select the best.
2653static void TryUserDefinedConversion(Sema &S,
2654 const InitializedEntity &Entity,
2655 const InitializationKind &Kind,
2656 Expr *Initializer,
2657 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002658 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2659
Douglas Gregor1b303932009-12-22 15:35:07 +00002660 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002661 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2662 QualType SourceType = Initializer->getType();
2663 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2664 "Must have a class type to perform a user-defined conversion");
2665
2666 // Build the candidate set directly in the initialization sequence
2667 // structure, so that it will persist if we fail.
2668 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2669 CandidateSet.clear();
2670
2671 // Determine whether we are allowed to call explicit constructors or
2672 // explicit conversion operators.
2673 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2674
2675 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2676 // The type we're converting to is a class type. Enumerate its constructors
2677 // to see if there is a suitable conversion.
2678 CXXRecordDecl *DestRecordDecl
2679 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2680
2681 DeclarationName ConstructorName
2682 = S.Context.DeclarationNames.getCXXConstructorName(
2683 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2684 DeclContext::lookup_iterator Con, ConEnd;
2685 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2686 Con != ConEnd; ++Con) {
2687 // Find the constructor (which may be a template).
2688 CXXConstructorDecl *Constructor = 0;
2689 FunctionTemplateDecl *ConstructorTmpl
2690 = dyn_cast<FunctionTemplateDecl>(*Con);
2691 if (ConstructorTmpl)
2692 Constructor = cast<CXXConstructorDecl>(
2693 ConstructorTmpl->getTemplatedDecl());
2694 else
2695 Constructor = cast<CXXConstructorDecl>(*Con);
2696
2697 if (!Constructor->isInvalidDecl() &&
2698 Constructor->isConvertingConstructor(AllowExplicit)) {
2699 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002700 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2701 ConstructorTmpl->getAccess(),
2702 /*ExplicitArgs*/ 0,
Douglas Gregor540c3b02009-12-14 17:27:33 +00002703 &Initializer, 1, CandidateSet);
2704 else
John McCallb89836b2010-01-26 01:37:31 +00002705 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2706 &Initializer, 1, CandidateSet);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002707 }
2708 }
2709 }
Eli Friedman78275202009-12-19 08:11:05 +00002710
2711 SourceLocation DeclLoc = Initializer->getLocStart();
2712
Douglas Gregor540c3b02009-12-14 17:27:33 +00002713 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2714 // The type we're converting from is a class type, enumerate its conversion
2715 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002716
Eli Friedman4afe9a32009-12-20 22:12:03 +00002717 // We can only enumerate the conversion functions for a complete type; if
2718 // the type isn't complete, simply skip this step.
2719 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2720 CXXRecordDecl *SourceRecordDecl
2721 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002722
John McCallad371252010-01-20 00:46:10 +00002723 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002724 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002725 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002726 E = Conversions->end();
2727 I != E; ++I) {
2728 NamedDecl *D = *I;
2729 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2730 if (isa<UsingShadowDecl>(D))
2731 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2732
2733 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2734 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002735 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002736 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002737 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002738 Conv = cast<CXXConversionDecl>(*I);
2739
2740 if (AllowExplicit || !Conv->isExplicit()) {
2741 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00002742 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2743 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002744 CandidateSet);
2745 else
John McCallb89836b2010-01-26 01:37:31 +00002746 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2747 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002748 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002749 }
2750 }
2751 }
2752
Douglas Gregor540c3b02009-12-14 17:27:33 +00002753 // Perform overload resolution. If it fails, return the failed result.
2754 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002755 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002756 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2757 Sequence.SetOverloadFailure(
2758 InitializationSequence::FK_UserConversionOverloadFailed,
2759 Result);
2760 return;
2761 }
John McCall0d1da222010-01-12 00:44:57 +00002762
Douglas Gregor540c3b02009-12-14 17:27:33 +00002763 FunctionDecl *Function = Best->Function;
2764
2765 if (isa<CXXConstructorDecl>(Function)) {
2766 // Add the user-defined conversion step. Any cv-qualification conversion is
2767 // subsumed by the initialization.
2768 Sequence.AddUserConversionStep(Function, DestType);
2769 return;
2770 }
2771
2772 // Add the user-defined conversion step that calls the conversion function.
2773 QualType ConvType = Function->getResultType().getNonReferenceType();
2774 Sequence.AddUserConversionStep(Function, ConvType);
2775
2776 // If the conversion following the call to the conversion function is
2777 // interesting, add it as a separate step.
2778 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2779 Best->FinalConversion.Third) {
2780 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002781 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002782 ICS.Standard = Best->FinalConversion;
2783 Sequence.AddConversionSequenceStep(ICS, DestType);
2784 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785}
2786
2787/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2788/// non-class type to another.
2789static void TryImplicitConversion(Sema &S,
2790 const InitializedEntity &Entity,
2791 const InitializationKind &Kind,
2792 Expr *Initializer,
2793 InitializationSequence &Sequence) {
2794 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002795 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002796 /*SuppressUserConversions=*/true,
2797 /*AllowExplicit=*/false,
2798 /*ForceRValue=*/false,
2799 /*FIXME:InOverloadResolution=*/false,
2800 /*UserCast=*/Kind.isExplicitCast());
2801
John McCall0d1da222010-01-12 00:44:57 +00002802 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002803 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2804 return;
2805 }
2806
Douglas Gregor1b303932009-12-22 15:35:07 +00002807 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002808}
2809
2810InitializationSequence::InitializationSequence(Sema &S,
2811 const InitializedEntity &Entity,
2812 const InitializationKind &Kind,
2813 Expr **Args,
2814 unsigned NumArgs) {
2815 ASTContext &Context = S.Context;
2816
2817 // C++0x [dcl.init]p16:
2818 // The semantics of initializers are as follows. The destination type is
2819 // the type of the object or reference being initialized and the source
2820 // type is the type of the initializer expression. The source type is not
2821 // defined when the initializer is a braced-init-list or when it is a
2822 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002823 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002824
2825 if (DestType->isDependentType() ||
2826 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2827 SequenceKind = DependentSequence;
2828 return;
2829 }
2830
2831 QualType SourceType;
2832 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002833 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002834 Initializer = Args[0];
2835 if (!isa<InitListExpr>(Initializer))
2836 SourceType = Initializer->getType();
2837 }
2838
2839 // - If the initializer is a braced-init-list, the object is
2840 // list-initialized (8.5.4).
2841 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2842 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002843 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002844 }
2845
2846 // - If the destination type is a reference type, see 8.5.3.
2847 if (DestType->isReferenceType()) {
2848 // C++0x [dcl.init.ref]p1:
2849 // A variable declared to be a T& or T&&, that is, "reference to type T"
2850 // (8.3.2), shall be initialized by an object, or function, of type T or
2851 // by an object that can be converted into a T.
2852 // (Therefore, multiple arguments are not permitted.)
2853 if (NumArgs != 1)
2854 SetFailed(FK_TooManyInitsForReference);
2855 else
2856 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2857 return;
2858 }
2859
2860 // - If the destination type is an array of characters, an array of
2861 // char16_t, an array of char32_t, or an array of wchar_t, and the
2862 // initializer is a string literal, see 8.5.2.
2863 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2864 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2865 return;
2866 }
2867
2868 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002869 if (Kind.getKind() == InitializationKind::IK_Value ||
2870 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002871 TryValueInitialization(S, Entity, Kind, *this);
2872 return;
2873 }
2874
Douglas Gregor85dabae2009-12-16 01:38:02 +00002875 // Handle default initialization.
2876 if (Kind.getKind() == InitializationKind::IK_Default){
2877 TryDefaultInitialization(S, Entity, Kind, *this);
2878 return;
2879 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002880
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002881 // - Otherwise, if the destination type is an array, the program is
2882 // ill-formed.
2883 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2884 if (AT->getElementType()->isAnyCharacterType())
2885 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2886 else
2887 SetFailed(FK_ArrayNeedsInitList);
2888
2889 return;
2890 }
Eli Friedman78275202009-12-19 08:11:05 +00002891
2892 // Handle initialization in C
2893 if (!S.getLangOptions().CPlusPlus) {
2894 setSequenceKind(CAssignment);
2895 AddCAssignmentStep(DestType);
2896 return;
2897 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002898
2899 // - If the destination type is a (possibly cv-qualified) class type:
2900 if (DestType->isRecordType()) {
2901 // - If the initialization is direct-initialization, or if it is
2902 // copy-initialization where the cv-unqualified version of the
2903 // source type is the same class as, or a derived class of, the
2904 // class of the destination, constructors are considered. [...]
2905 if (Kind.getKind() == InitializationKind::IK_Direct ||
2906 (Kind.getKind() == InitializationKind::IK_Copy &&
2907 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2908 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002909 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002910 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002911 // - Otherwise (i.e., for the remaining copy-initialization cases),
2912 // user-defined conversion sequences that can convert from the source
2913 // type to the destination type or (when a conversion function is
2914 // used) to a derived class thereof are enumerated as described in
2915 // 13.3.1.4, and the best one is chosen through overload resolution
2916 // (13.3).
2917 else
2918 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2919 return;
2920 }
2921
Douglas Gregor85dabae2009-12-16 01:38:02 +00002922 if (NumArgs > 1) {
2923 SetFailed(FK_TooManyInitsForScalar);
2924 return;
2925 }
2926 assert(NumArgs == 1 && "Zero-argument case handled above");
2927
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002928 // - Otherwise, if the source type is a (possibly cv-qualified) class
2929 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002930 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002931 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2932 return;
2933 }
2934
2935 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002936 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002937 // conversions (Clause 4) will be used, if necessary, to convert the
2938 // initializer expression to the cv-unqualified version of the
2939 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002940 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002941 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2942}
2943
2944InitializationSequence::~InitializationSequence() {
2945 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2946 StepEnd = Steps.end();
2947 Step != StepEnd; ++Step)
2948 Step->Destroy();
2949}
2950
2951//===----------------------------------------------------------------------===//
2952// Perform initialization
2953//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002954static Sema::AssignmentAction
2955getAssignmentAction(const InitializedEntity &Entity) {
2956 switch(Entity.getKind()) {
2957 case InitializedEntity::EK_Variable:
2958 case InitializedEntity::EK_New:
2959 return Sema::AA_Initializing;
2960
2961 case InitializedEntity::EK_Parameter:
2962 // FIXME: Can we tell when we're sending vs. passing?
2963 return Sema::AA_Passing;
2964
2965 case InitializedEntity::EK_Result:
2966 return Sema::AA_Returning;
2967
2968 case InitializedEntity::EK_Exception:
2969 case InitializedEntity::EK_Base:
2970 llvm_unreachable("No assignment action for C++-specific initialization");
2971 break;
2972
2973 case InitializedEntity::EK_Temporary:
2974 // FIXME: Can we tell apart casting vs. converting?
2975 return Sema::AA_Casting;
2976
2977 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002978 case InitializedEntity::EK_ArrayElement:
2979 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00002980 return Sema::AA_Initializing;
2981 }
2982
2983 return Sema::AA_Converting;
2984}
2985
2986static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2987 bool IsCopy) {
2988 switch (Entity.getKind()) {
2989 case InitializedEntity::EK_Result:
2990 case InitializedEntity::EK_Exception:
Anders Carlsson0bd52402010-01-24 00:19:41 +00002991 case InitializedEntity::EK_ArrayElement:
2992 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00002993 return !IsCopy;
2994
2995 case InitializedEntity::EK_New:
2996 case InitializedEntity::EK_Variable:
2997 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002998 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00002999 return false;
3000
3001 case InitializedEntity::EK_Parameter:
3002 case InitializedEntity::EK_Temporary:
3003 return true;
3004 }
3005
3006 llvm_unreachable("missed an InitializedEntity kind?");
3007}
3008
3009/// \brief If we need to perform an additional copy of the initialized object
3010/// for this kind of entity (e.g., the result of a function or an object being
3011/// thrown), make the copy.
3012static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3013 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003014 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003015 Sema::OwningExprResult CurInit) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003016 Expr *CurInitExpr = (Expr *)CurInit.get();
3017
Douglas Gregore1314a62009-12-18 05:02:21 +00003018 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003019
3020 switch (Entity.getKind()) {
3021 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003022 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003023 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003024 Loc = Entity.getReturnLoc();
3025 break;
3026
3027 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003028 Loc = Entity.getThrowLoc();
3029 break;
3030
3031 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003032 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003033 Kind.getKind() != InitializationKind::IK_Copy)
3034 return move(CurInit);
3035 Loc = Entity.getDecl()->getLocation();
3036 break;
3037
Anders Carlsson0bd52402010-01-24 00:19:41 +00003038 case InitializedEntity::EK_ArrayElement:
3039 case InitializedEntity::EK_Member:
3040 if (Entity.getType()->isReferenceType() ||
3041 Kind.getKind() != InitializationKind::IK_Copy)
3042 return move(CurInit);
3043 Loc = CurInitExpr->getLocStart();
3044 break;
3045
Douglas Gregore1314a62009-12-18 05:02:21 +00003046 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003047 // FIXME: Do we need this initialization for a parameter?
3048 return move(CurInit);
3049
Douglas Gregore1314a62009-12-18 05:02:21 +00003050 case InitializedEntity::EK_New:
3051 case InitializedEntity::EK_Temporary:
3052 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003053 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003054 // We don't need to copy for any of these initialized entities.
3055 return move(CurInit);
3056 }
3057
Douglas Gregore1314a62009-12-18 05:02:21 +00003058 CXXRecordDecl *Class = 0;
3059 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3060 Class = cast<CXXRecordDecl>(Record->getDecl());
3061 if (!Class)
3062 return move(CurInit);
3063
3064 // Perform overload resolution using the class's copy constructors.
3065 DeclarationName ConstructorName
3066 = S.Context.DeclarationNames.getCXXConstructorName(
3067 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3068 DeclContext::lookup_iterator Con, ConEnd;
3069 OverloadCandidateSet CandidateSet;
3070 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3071 Con != ConEnd; ++Con) {
3072 // Find the constructor (which may be a template).
3073 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3074 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003075 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003076 continue;
3077
John McCallb89836b2010-01-26 01:37:31 +00003078 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
3079 &CurInitExpr, 1, CandidateSet);
Douglas Gregore1314a62009-12-18 05:02:21 +00003080 }
3081
3082 OverloadCandidateSet::iterator Best;
3083 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3084 case OR_Success:
3085 break;
3086
3087 case OR_No_Viable_Function:
3088 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003089 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003090 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003091 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3092 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003093 return S.ExprError();
3094
3095 case OR_Ambiguous:
3096 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003097 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003098 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003099 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3100 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003101 return S.ExprError();
3102
3103 case OR_Deleted:
3104 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003105 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003106 << CurInitExpr->getSourceRange();
3107 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3108 << Best->Function->isDeleted();
3109 return S.ExprError();
3110 }
3111
3112 CurInit.release();
3113 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3114 cast<CXXConstructorDecl>(Best->Function),
3115 /*Elidable=*/true,
3116 Sema::MultiExprArg(S,
3117 (void**)&CurInitExpr, 1));
3118}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119
3120Action::OwningExprResult
3121InitializationSequence::Perform(Sema &S,
3122 const InitializedEntity &Entity,
3123 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003124 Action::MultiExprArg Args,
3125 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003126 if (SequenceKind == FailedSequence) {
3127 unsigned NumArgs = Args.size();
3128 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3129 return S.ExprError();
3130 }
3131
3132 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003133 // If the declaration is a non-dependent, incomplete array type
3134 // that has an initializer, then its type will be completed once
3135 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003136 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003137 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003138 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003139 if (const IncompleteArrayType *ArrayT
3140 = S.Context.getAsIncompleteArrayType(DeclType)) {
3141 // FIXME: We don't currently have the ability to accurately
3142 // compute the length of an initializer list without
3143 // performing full type-checking of the initializer list
3144 // (since we have to determine where braces are implicitly
3145 // introduced and such). So, we fall back to making the array
3146 // type a dependently-sized array type with no specified
3147 // bound.
3148 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3149 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003150
Douglas Gregor51e77d52009-12-10 17:56:55 +00003151 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003152 if (DeclaratorDecl *DD = Entity.getDecl()) {
3153 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3154 TypeLoc TL = TInfo->getTypeLoc();
3155 if (IncompleteArrayTypeLoc *ArrayLoc
3156 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3157 Brackets = ArrayLoc->getBracketsRange();
3158 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003159 }
3160
3161 *ResultType
3162 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3163 /*NumElts=*/0,
3164 ArrayT->getSizeModifier(),
3165 ArrayT->getIndexTypeCVRQualifiers(),
3166 Brackets);
3167 }
3168
3169 }
3170 }
3171
Eli Friedmana553d4a2009-12-22 02:35:53 +00003172 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003173 return Sema::OwningExprResult(S, Args.release()[0]);
3174
3175 unsigned NumArgs = Args.size();
3176 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3177 SourceLocation(),
3178 (Expr **)Args.release(),
3179 NumArgs,
3180 SourceLocation()));
3181 }
3182
Douglas Gregor85dabae2009-12-16 01:38:02 +00003183 if (SequenceKind == NoInitialization)
3184 return S.Owned((Expr *)0);
3185
Douglas Gregor1b303932009-12-22 15:35:07 +00003186 QualType DestType = Entity.getType().getNonReferenceType();
3187 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003188 // the same as Entity.getDecl()->getType() in cases involving type merging,
3189 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003190 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003191 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003192 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003193
Douglas Gregor85dabae2009-12-16 01:38:02 +00003194 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3195
3196 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3197
3198 // For initialization steps that start with a single initializer,
3199 // grab the only argument out the Args and place it into the "current"
3200 // initializer.
3201 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003202 case SK_ResolveAddressOfOverloadedFunction:
3203 case SK_CastDerivedToBaseRValue:
3204 case SK_CastDerivedToBaseLValue:
3205 case SK_BindReference:
3206 case SK_BindReferenceToTemporary:
3207 case SK_UserConversion:
3208 case SK_QualificationConversionLValue:
3209 case SK_QualificationConversionRValue:
3210 case SK_ConversionSequence:
3211 case SK_ListInitialization:
3212 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003213 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003214 assert(Args.size() == 1);
3215 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3216 if (CurInit.isInvalid())
3217 return S.ExprError();
3218 break;
3219
3220 case SK_ConstructorInitialization:
3221 case SK_ZeroInitialization:
3222 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003223 }
3224
3225 // Walk through the computed steps for the initialization sequence,
3226 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003227 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228 for (step_iterator Step = step_begin(), StepEnd = step_end();
3229 Step != StepEnd; ++Step) {
3230 if (CurInit.isInvalid())
3231 return S.ExprError();
3232
3233 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003234 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003235
3236 switch (Step->Kind) {
3237 case SK_ResolveAddressOfOverloadedFunction:
3238 // Overload resolution determined which function invoke; update the
3239 // initializer to reflect that choice.
3240 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3241 break;
3242
3243 case SK_CastDerivedToBaseRValue:
3244 case SK_CastDerivedToBaseLValue: {
3245 // We have a derived-to-base cast that produces either an rvalue or an
3246 // lvalue. Perform that cast.
3247
3248 // Casts to inaccessible base classes are allowed with C-style casts.
3249 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3250 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3251 CurInitExpr->getLocStart(),
3252 CurInitExpr->getSourceRange(),
3253 IgnoreBaseAccess))
3254 return S.ExprError();
3255
3256 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3257 CastExpr::CK_DerivedToBase,
3258 (Expr*)CurInit.release(),
3259 Step->Kind == SK_CastDerivedToBaseLValue));
3260 break;
3261 }
3262
3263 case SK_BindReference:
3264 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3265 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3266 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003267 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003268 << BitField->getDeclName()
3269 << CurInitExpr->getSourceRange();
3270 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3271 return S.ExprError();
3272 }
3273
3274 // Reference binding does not have any corresponding ASTs.
3275
3276 // Check exception specifications
3277 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3278 return S.ExprError();
3279 break;
3280
3281 case SK_BindReferenceToTemporary:
3282 // Check exception specifications
3283 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3284 return S.ExprError();
3285
3286 // FIXME: At present, we have no AST to describe when we need to make a
3287 // temporary to bind a reference to. We should.
3288 break;
3289
3290 case SK_UserConversion: {
3291 // We have a user-defined conversion that invokes either a constructor
3292 // or a conversion function.
3293 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003294 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003295 if (CXXConstructorDecl *Constructor
3296 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3297 // Build a call to the selected constructor.
3298 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3299 SourceLocation Loc = CurInitExpr->getLocStart();
3300 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3301
3302 // Determine the arguments required to actually perform the constructor
3303 // call.
3304 if (S.CompleteConstructorCall(Constructor,
3305 Sema::MultiExprArg(S,
3306 (void **)&CurInitExpr,
3307 1),
3308 Loc, ConstructorArgs))
3309 return S.ExprError();
3310
3311 // Build the an expression that constructs a temporary.
3312 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3313 move_arg(ConstructorArgs));
3314 if (CurInit.isInvalid())
3315 return S.ExprError();
3316
3317 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003318 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3319 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3320 S.IsDerivedFrom(SourceType, Class))
3321 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003322 } else {
3323 // Build a call to the conversion function.
3324 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003325
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003326 // FIXME: Should we move this initialization into a separate
3327 // derived-to-base conversion? I believe the answer is "no", because
3328 // we don't want to turn off access control here for c-style casts.
3329 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3330 return S.ExprError();
3331
3332 // Do a little dance to make sure that CurInit has the proper
3333 // pointer.
3334 CurInit.release();
3335
3336 // Build the actual call to the conversion function.
3337 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3338 if (CurInit.isInvalid() || !CurInit.get())
3339 return S.ExprError();
3340
3341 CastKind = CastExpr::CK_UserDefinedConversion;
3342 }
3343
Douglas Gregore1314a62009-12-18 05:02:21 +00003344 if (shouldBindAsTemporary(Entity, IsCopy))
3345 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3346
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003347 CurInitExpr = CurInit.takeAs<Expr>();
3348 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3349 CastKind,
3350 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003351 false));
3352
3353 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003354 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003355 break;
3356 }
3357
3358 case SK_QualificationConversionLValue:
3359 case SK_QualificationConversionRValue:
3360 // Perform a qualification conversion; these can never go wrong.
3361 S.ImpCastExprToType(CurInitExpr, Step->Type,
3362 CastExpr::CK_NoOp,
3363 Step->Kind == SK_QualificationConversionLValue);
3364 CurInit.release();
3365 CurInit = S.Owned(CurInitExpr);
3366 break;
3367
3368 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003369 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003370 false, false, *Step->ICS))
3371 return S.ExprError();
3372
3373 CurInit.release();
3374 CurInit = S.Owned(CurInitExpr);
3375 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003376
3377 case SK_ListInitialization: {
3378 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3379 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003380 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003381 return S.ExprError();
3382
3383 CurInit.release();
3384 CurInit = S.Owned(InitList);
3385 break;
3386 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003387
3388 case SK_ConstructorInitialization: {
3389 CXXConstructorDecl *Constructor
3390 = cast<CXXConstructorDecl>(Step->Function);
3391
3392 // Build a call to the selected constructor.
3393 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3394 SourceLocation Loc = Kind.getLocation();
3395
3396 // Determine the arguments required to actually perform the constructor
3397 // call.
3398 if (S.CompleteConstructorCall(Constructor, move(Args),
3399 Loc, ConstructorArgs))
3400 return S.ExprError();
3401
3402 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003403 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003404 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003405 move_arg(ConstructorArgs),
3406 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003407 if (CurInit.isInvalid())
3408 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003409
3410 bool Elidable
3411 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3412 if (shouldBindAsTemporary(Entity, Elidable))
3413 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3414
3415 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003416 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003417 break;
3418 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003419
3420 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003421 step_iterator NextStep = Step;
3422 ++NextStep;
3423 if (NextStep != StepEnd &&
3424 NextStep->Kind == SK_ConstructorInitialization) {
3425 // The need for zero-initialization is recorded directly into
3426 // the call to the object's constructor within the next step.
3427 ConstructorInitRequiresZeroInit = true;
3428 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3429 S.getLangOptions().CPlusPlus &&
3430 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003431 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3432 Kind.getRange().getBegin(),
3433 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003434 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003435 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003436 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003437 break;
3438 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003439
3440 case SK_CAssignment: {
3441 QualType SourceType = CurInitExpr->getType();
3442 Sema::AssignConvertType ConvTy =
3443 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003444
3445 // If this is a call, allow conversion to a transparent union.
3446 if (ConvTy != Sema::Compatible &&
3447 Entity.getKind() == InitializedEntity::EK_Parameter &&
3448 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3449 == Sema::Compatible)
3450 ConvTy = Sema::Compatible;
3451
Douglas Gregore1314a62009-12-18 05:02:21 +00003452 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3453 Step->Type, SourceType,
3454 CurInitExpr, getAssignmentAction(Entity)))
3455 return S.ExprError();
3456
3457 CurInit.release();
3458 CurInit = S.Owned(CurInitExpr);
3459 break;
3460 }
Eli Friedman78275202009-12-19 08:11:05 +00003461
3462 case SK_StringInit: {
3463 QualType Ty = Step->Type;
3464 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3465 break;
3466 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467 }
3468 }
3469
3470 return move(CurInit);
3471}
3472
3473//===----------------------------------------------------------------------===//
3474// Diagnose initialization failures
3475//===----------------------------------------------------------------------===//
3476bool InitializationSequence::Diagnose(Sema &S,
3477 const InitializedEntity &Entity,
3478 const InitializationKind &Kind,
3479 Expr **Args, unsigned NumArgs) {
3480 if (SequenceKind != FailedSequence)
3481 return false;
3482
Douglas Gregor1b303932009-12-22 15:35:07 +00003483 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003484 switch (Failure) {
3485 case FK_TooManyInitsForReference:
3486 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3487 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3488 break;
3489
3490 case FK_ArrayNeedsInitList:
3491 case FK_ArrayNeedsInitListOrStringLiteral:
3492 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3493 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3494 break;
3495
3496 case FK_AddressOfOverloadFailed:
3497 S.ResolveAddressOfOverloadedFunction(Args[0],
3498 DestType.getNonReferenceType(),
3499 true);
3500 break;
3501
3502 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003503 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003504 switch (FailedOverloadResult) {
3505 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003506 if (Failure == FK_UserConversionOverloadFailed)
3507 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3508 << Args[0]->getType() << DestType
3509 << Args[0]->getSourceRange();
3510 else
3511 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3512 << DestType << Args[0]->getType()
3513 << Args[0]->getSourceRange();
3514
John McCallad907772010-01-12 07:18:19 +00003515 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3516 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003517 break;
3518
3519 case OR_No_Viable_Function:
3520 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3521 << Args[0]->getType() << DestType.getNonReferenceType()
3522 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003523 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3524 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003525 break;
3526
3527 case OR_Deleted: {
3528 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3529 << Args[0]->getType() << DestType.getNonReferenceType()
3530 << Args[0]->getSourceRange();
3531 OverloadCandidateSet::iterator Best;
3532 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3533 Kind.getLocation(),
3534 Best);
3535 if (Ovl == OR_Deleted) {
3536 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3537 << Best->Function->isDeleted();
3538 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003539 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003540 }
3541 break;
3542 }
3543
3544 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003545 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003546 break;
3547 }
3548 break;
3549
3550 case FK_NonConstLValueReferenceBindingToTemporary:
3551 case FK_NonConstLValueReferenceBindingToUnrelated:
3552 S.Diag(Kind.getLocation(),
3553 Failure == FK_NonConstLValueReferenceBindingToTemporary
3554 ? diag::err_lvalue_reference_bind_to_temporary
3555 : diag::err_lvalue_reference_bind_to_unrelated)
3556 << DestType.getNonReferenceType()
3557 << Args[0]->getType()
3558 << Args[0]->getSourceRange();
3559 break;
3560
3561 case FK_RValueReferenceBindingToLValue:
3562 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3563 << Args[0]->getSourceRange();
3564 break;
3565
3566 case FK_ReferenceInitDropsQualifiers:
3567 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3568 << DestType.getNonReferenceType()
3569 << Args[0]->getType()
3570 << Args[0]->getSourceRange();
3571 break;
3572
3573 case FK_ReferenceInitFailed:
3574 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3575 << DestType.getNonReferenceType()
3576 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3577 << Args[0]->getType()
3578 << Args[0]->getSourceRange();
3579 break;
3580
3581 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003582 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3583 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003584 << DestType
3585 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3586 << Args[0]->getType()
3587 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003588 break;
3589
3590 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003591 SourceRange R;
3592
3593 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3594 R = SourceRange(InitList->getInit(1)->getLocStart(),
3595 InitList->getLocEnd());
3596 else
3597 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003598
3599 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003600 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003601 break;
3602 }
3603
3604 case FK_ReferenceBindingToInitList:
3605 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3606 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3607 break;
3608
3609 case FK_InitListBadDestinationType:
3610 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3611 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3612 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003613
3614 case FK_ConstructorOverloadFailed: {
3615 SourceRange ArgsRange;
3616 if (NumArgs)
3617 ArgsRange = SourceRange(Args[0]->getLocStart(),
3618 Args[NumArgs - 1]->getLocEnd());
3619
3620 // FIXME: Using "DestType" for the entity we're printing is probably
3621 // bad.
3622 switch (FailedOverloadResult) {
3623 case OR_Ambiguous:
3624 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3625 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003626 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003627 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003628 break;
3629
3630 case OR_No_Viable_Function:
3631 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3632 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003633 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3634 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003635 break;
3636
3637 case OR_Deleted: {
3638 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3639 << true << DestType << ArgsRange;
3640 OverloadCandidateSet::iterator Best;
3641 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3642 Kind.getLocation(),
3643 Best);
3644 if (Ovl == OR_Deleted) {
3645 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3646 << Best->Function->isDeleted();
3647 } else {
3648 llvm_unreachable("Inconsistent overload resolution?");
3649 }
3650 break;
3651 }
3652
3653 case OR_Success:
3654 llvm_unreachable("Conversion did not fail!");
3655 break;
3656 }
3657 break;
3658 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003659
3660 case FK_DefaultInitOfConst:
3661 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3662 << DestType;
3663 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003664 }
3665
3666 return true;
3667}
Douglas Gregore1314a62009-12-18 05:02:21 +00003668
3669//===----------------------------------------------------------------------===//
3670// Initialization helper functions
3671//===----------------------------------------------------------------------===//
3672Sema::OwningExprResult
3673Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3674 SourceLocation EqualLoc,
3675 OwningExprResult Init) {
3676 if (Init.isInvalid())
3677 return ExprError();
3678
3679 Expr *InitE = (Expr *)Init.get();
3680 assert(InitE && "No initialization expression?");
3681
3682 if (EqualLoc.isInvalid())
3683 EqualLoc = InitE->getLocStart();
3684
3685 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3686 EqualLoc);
3687 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3688 Init.release();
3689 return Seq.Perform(*this, Entity, Kind,
3690 MultiExprArg(*this, (void**)&InitE, 1));
3691}