blob: a4d0b5164bd7a305e4e5d42468499de66c160ce0 [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
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Sema.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000022#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattnerd8b741c82009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman893abe42009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattnera9196812009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnera9196812009-02-26 23:26:43 +000045 // Handle @encode, which is a narrow string.
46 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 return Init;
48
49 // Otherwise we can only handle string literals.
50 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000054 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000058
Eli Friedman42a84652009-05-31 10:54:53 +000059 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60 // correction from DR343): "An array with element type compatible with a
61 // qualified or unqualified version of wchar_t may be initialized by a wide
62 // string literal, optionally enclosed in braces."
63 if (Context.typesAreCompatible(Context.getWCharType(),
64 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000065 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattner0cb78032009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattnerd8b741c82009-02-24 23:10:27 +000070static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71 // Get the length of the string as parsed.
72 uint64_t StrLength =
73 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000086 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000087 }
Mike Stump11289f42009-09-09 15:08:12 +000088
Eli Friedman893abe42009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000090
Eli Friedman893abe42009-05-29 18:22:49 +000091 // C99 6.7.8p14. We have an array of character type with known size. However,
92 // the size may be smaller or larger than the string we are initializing.
93 // FIXME: Avoid truncation for 64-bit length strings.
94 if (StrLength-1 > CAT->getSize().getZExtValue())
95 S.Diag(Str->getSourceRange().getBegin(),
96 diag::warn_initializer_string_for_char_array_too_long)
97 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000098
Eli Friedman893abe42009-05-29 18:22:49 +000099 // Set the type to the actual size that we are initializing. If we have
100 // something like:
101 // char x[1] = "foo";
102 // then this will set the string literal's type to char[1].
103 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000104}
105
Chris Lattner0cb78032009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregorcde232f2009-01-29 01:05:33 +0000110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000137namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000143
Anders Carlsson6cabf312010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000204 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205 QualType CurrentObjectType,
206 InitListExpr *StructuredList,
207 unsigned StructuredIndex,
208 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000214
Douglas Gregor2bb07652009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000223 bool HadError() { return hadError; }
224
225 // @brief Retrieves the fully-structured initializer list used for
226 // semantic analysis and code generation.
227 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
Chris Lattner9ececce2009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000230
Douglas Gregor2bb07652009-12-22 00:05:34 +0000231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232 const InitializedEntity &ParentEntity,
233 InitListExpr *ILE,
234 bool &RequiresSecondPass) {
235 SourceLocation Loc = ILE->getSourceRange().getBegin();
236 unsigned NumInits = ILE->getNumInits();
237 InitializedEntity MemberEntity
238 = InitializedEntity::InitializeMember(Field, &ParentEntity);
239 if (Init >= NumInits || !ILE->getInit(Init)) {
240 // FIXME: We probably don't need to handle references
241 // specially here, since value-initialization of references is
242 // handled in InitializationSequence.
243 if (Field->getType()->isReferenceType()) {
244 // C++ [dcl.init.aggr]p9:
245 // If an incomplete or empty initializer-list leaves a
246 // member of reference type uninitialized, the program is
247 // ill-formed.
248 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249 << Field->getType()
250 << ILE->getSyntacticForm()->getSourceRange();
251 SemaRef.Diag(Field->getLocation(),
252 diag::note_uninit_reference_member);
253 hadError = true;
254 return;
255 }
256
257 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258 true);
259 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260 if (!InitSeq) {
261 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262 hadError = true;
263 return;
264 }
265
John McCalldadc5752010-08-24 06:29:42 +0000266 ExprResult MemberInit
Douglas Gregor2bb07652009-12-22 00:05:34 +0000267 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268 Sema::MultiExprArg(SemaRef, 0, 0));
269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000319
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000321 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000328
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Douglas Gregor723796a2009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000354 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor723796a2009-12-16 06:35:08 +0000357
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
John McCalldadc5752010-08-24 06:29:42 +0000376 ExprResult ElementInit
Douglas Gregor723796a2009-12-16 06:35:08 +0000377 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378 Sema::MultiExprArg(SemaRef, 0, 0));
379 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000381 return;
382 }
383
384 if (hadError) {
385 // Do nothing
386 } else if (Init < NumInits) {
387 ILE->setInit(Init, ElementInit.takeAs<Expr>());
388 } else if (InitSeq.getKind()
389 == InitializationSequence::ConstructorInitialization) {
390 // Value-initialization requires a constructor call, so
391 // extend the initializer list to include the constructor
392 // call and make a note that we'll need to take another pass
393 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000394 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000403
Douglas Gregor723796a2009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000408
Eli Friedman23a9e312008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000416
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000431 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432 }
433 return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000449}
450
Anders Carlsson6cabf312010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000458
Steve Narofff8ecff22008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000461 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000462 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000467
Eli Friedmane0f832b2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000471 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000483
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregor5741efb2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000507 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
508 "{")
509 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000510 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000511 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000512 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000513}
514
Anders Carlsson6cabf312010-01-23 23:23:01 +0000515void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000516 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000517 unsigned &Index,
518 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000519 unsigned &StructuredIndex,
520 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000521 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 SyntacticToSemantic[IList] = StructuredList;
523 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000524 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
525 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000526 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
527 IList->setType(ExprTy);
528 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000529 if (hadError)
530 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000531
Eli Friedman85f54972008-05-25 13:22:35 +0000532 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000533 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000534 if (StructuredIndex == 1 &&
535 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000536 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000537 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000538 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000539 hadError = true;
540 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000541 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000542 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000543 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000544 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000545 // Don't complain for incomplete types, since we'll get an error
546 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000547 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000548 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000549 CurrentObjectType->isArrayType()? 0 :
550 CurrentObjectType->isVectorType()? 1 :
551 CurrentObjectType->isScalarType()? 2 :
552 CurrentObjectType->isUnionType()? 3 :
553 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000554
555 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000556 if (SemaRef.getLangOptions().CPlusPlus) {
557 DK = diag::err_excess_initializers;
558 hadError = true;
559 }
Nate Begeman425038c2009-07-07 21:53:06 +0000560 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
561 DK = diag::err_excess_initializers;
562 hadError = true;
563 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000564
Chris Lattnerb0912a52009-02-24 22:50:46 +0000565 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000566 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000567 }
568 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000569
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000570 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000571 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000572 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000573 << FixItHint::CreateRemoval(IList->getLocStart())
574 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000575}
576
Anders Carlsson6cabf312010-01-23 23:23:01 +0000577void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000578 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000579 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000580 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000581 unsigned &Index,
582 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000583 unsigned &StructuredIndex,
584 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000585 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000586 CheckScalarType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000588 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000589 CheckVectorType(Entity, IList, DeclType, Index,
590 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000591 } else if (DeclType->isAggregateType()) {
592 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000593 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000594 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000596 StructuredList, StructuredIndex,
597 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000598 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000599 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000600 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000601 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000602 CheckArrayType(Entity, IList, DeclType, Zero,
603 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000604 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000605 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000606 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
608 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000609 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000611 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000612 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000613 } else if (DeclType->isRecordType()) {
614 // C++ [dcl.init]p14:
615 // [...] If the class is an aggregate (8.5.1), and the initializer
616 // is a brace-enclosed list, see 8.5.1.
617 //
618 // Note: 8.5.1 is handled below; here, we diagnose the case where
619 // we have an initializer list and a destination type that is not
620 // an aggregate.
621 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000623 << DeclType << IList->getSourceRange();
624 hadError = true;
625 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000626 CheckReferenceType(Entity, IList, DeclType, Index,
627 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000628 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000629 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
630 << DeclType;
631 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000632 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000633 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
634 << DeclType;
635 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000636 }
637}
638
Anders Carlsson6cabf312010-01-23 23:23:01 +0000639void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000640 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000641 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000642 unsigned &Index,
643 InitListExpr *StructuredList,
644 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000645 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000646 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
647 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000648 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000649 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000650 = getStructuredSubobjectInit(IList, Index, ElemType,
651 StructuredList, StructuredIndex,
652 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000653 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000654 newStructuredList, newStructuredIndex);
655 ++StructuredIndex;
656 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000657 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
658 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000659 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000660 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000661 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000662 CheckScalarType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000664 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000665 CheckReferenceType(Entity, IList, ElemType, Index,
666 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000667 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000668 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000669 // C++ [dcl.init.aggr]p12:
670 // All implicit type conversions (clause 4) are considered when
671 // initializing the aggregate member with an ini- tializer from
672 // an initializer-list. If the initializer can initialize a
673 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000674
Anders Carlsson0bd52402010-01-24 00:19:41 +0000675 // FIXME: Better EqualLoc?
676 InitializationKind Kind =
677 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
678 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
679
680 if (Seq) {
John McCalldadc5752010-08-24 06:29:42 +0000681 ExprResult Result =
Anders Carlsson0bd52402010-01-24 00:19:41 +0000682 Seq.Perform(SemaRef, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000683 Sema::MultiExprArg(SemaRef, &expr, 1));
Anders Carlsson0bd52402010-01-24 00:19:41 +0000684 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000685 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000686
687 UpdateStructuredListElement(StructuredList, StructuredIndex,
688 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000689 ++Index;
690 return;
691 }
692
693 // Fall through for subaggregate initialization
694 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000695 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000696 //
697 // The initializer for a structure or union object that has
698 // automatic storage duration shall be either an initializer
699 // list as described below, or a single expression that has
700 // compatible structure or union type. In the latter case, the
701 // initial value of the object, including unnamed members, is
702 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000703 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000704 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000705 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
706 ++Index;
707 return;
708 }
709
710 // Fall through for subaggregate initialization
711 }
712
713 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000714 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000715 // [...] Otherwise, if the member is itself a non-empty
716 // subaggregate, brace elision is assumed and the initializer is
717 // considered for the initialization of the first member of
718 // the subaggregate.
719 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000720 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000721 StructuredIndex);
722 ++StructuredIndex;
723 } else {
724 // We cannot initialize this element, so let
725 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000726 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
727 SemaRef.Owned(expr));
728 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000729 hadError = true;
730 ++Index;
731 ++StructuredIndex;
732 }
733 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000734}
735
Anders Carlsson6cabf312010-01-23 23:23:01 +0000736void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000737 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000738 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000739 InitListExpr *StructuredList,
740 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000741 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000742 Expr *expr = IList->getInit(Index);
Eli Friedmandf239252010-08-14 03:14:53 +0000743 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
744 SemaRef.Diag(SubIList->getLocStart(),
745 diag::warn_many_braces_around_scalar_init)
746 << SubIList->getSourceRange();
747
748 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
749 StructuredIndex);
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000750 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000751 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000752 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000753 diag::err_designator_for_scalar_init)
754 << DeclType << expr->getSourceRange();
755 hadError = true;
756 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000757 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000758 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000759 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000760
John McCalldadc5752010-08-24 06:29:42 +0000761 ExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000762 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
763 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000764
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000765 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000766
767 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000768 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000769 else {
770 ResultExpr = Result.takeAs<Expr>();
771
772 if (ResultExpr != expr) {
773 // The type was promoted, update initializer list.
774 IList->setInit(Index, ResultExpr);
775 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000776 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000777 if (hadError)
778 ++StructuredIndex;
779 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000780 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000781 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000782 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000783 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000784 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000785 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000786 ++Index;
787 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000788 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000789 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000790}
791
Anders Carlsson6cabf312010-01-23 23:23:01 +0000792void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
793 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000794 unsigned &Index,
795 InitListExpr *StructuredList,
796 unsigned &StructuredIndex) {
797 if (Index < IList->getNumInits()) {
798 Expr *expr = IList->getInit(Index);
799 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000800 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000801 << DeclType << IList->getSourceRange();
802 hadError = true;
803 ++Index;
804 ++StructuredIndex;
805 return;
Mike Stump11289f42009-09-09 15:08:12 +0000806 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000807
John McCalldadc5752010-08-24 06:29:42 +0000808 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000809 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
810 SemaRef.Owned(expr));
811
812 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000813 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000814
815 expr = Result.takeAs<Expr>();
816 IList->setInit(Index, expr);
817
Douglas Gregord14247a2009-01-30 22:09:00 +0000818 if (hadError)
819 ++StructuredIndex;
820 else
821 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
822 ++Index;
823 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000824 // FIXME: It would be wonderful if we could point at the actual member. In
825 // general, it would be useful to pass location information down the stack,
826 // so that we know the location (or decl) of the "current object" being
827 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000828 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000829 diag::err_init_reference_member_uninitialized)
830 << DeclType
831 << IList->getSourceRange();
832 hadError = true;
833 ++Index;
834 ++StructuredIndex;
835 return;
836 }
837}
838
Anders Carlsson6cabf312010-01-23 23:23:01 +0000839void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000840 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000841 unsigned &Index,
842 InitListExpr *StructuredList,
843 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000844 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000845 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000846 unsigned maxElements = VT->getNumElements();
847 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000848 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000849
Nate Begeman5ec4b312009-08-10 23:49:36 +0000850 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000851 InitializedEntity ElementEntity =
852 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000853
Anders Carlsson6cabf312010-01-23 23:23:01 +0000854 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
855 // Don't attempt to go past the end of the init list
856 if (Index >= IList->getNumInits())
857 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000858
Anders Carlsson6cabf312010-01-23 23:23:01 +0000859 ElementEntity.setElementIndex(Index);
860 CheckSubElementType(ElementEntity, IList, elementType, Index,
861 StructuredList, StructuredIndex);
862 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000863 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000864 InitializedEntity ElementEntity =
865 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
866
Nate Begeman5ec4b312009-08-10 23:49:36 +0000867 // OpenCL initializers allows vectors to be constructed from vectors.
868 for (unsigned i = 0; i < maxElements; ++i) {
869 // Don't attempt to go past the end of the init list
870 if (Index >= IList->getNumInits())
871 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000872
873 ElementEntity.setElementIndex(Index);
874
Nate Begeman5ec4b312009-08-10 23:49:36 +0000875 QualType IType = IList->getInit(Index)->getType();
876 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000877 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000878 StructuredList, StructuredIndex);
879 ++numEltsInit;
880 } else {
Nate Begeman5da51d32010-07-07 22:26:56 +0000881 QualType VecType;
John McCall9dd450b2009-09-21 23:43:11 +0000882 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000883 unsigned numIElts = IVT->getNumElements();
Nate Begeman5da51d32010-07-07 22:26:56 +0000884
885 if (IType->isExtVectorType())
886 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
887 else
888 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
889 IVT->getAltiVecSpecific());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000890 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000891 StructuredList, StructuredIndex);
892 numEltsInit += numIElts;
893 }
894 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
John Thompson7bc797b2010-04-20 23:21:17 +0000897 // OpenCL requires all elements to be initialized.
Nate Begeman5ec4b312009-08-10 23:49:36 +0000898 if (numEltsInit != maxElements)
Chris Lattnerb596ac72010-04-20 05:19:10 +0000899 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman5ec4b312009-08-10 23:49:36 +0000900 SemaRef.Diag(IList->getSourceRange().getBegin(),
901 diag::err_vector_incorrect_num_initializers)
902 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000903 }
904}
905
Anders Carlsson6cabf312010-01-23 23:23:01 +0000906void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000907 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000908 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000909 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000910 unsigned &Index,
911 InitListExpr *StructuredList,
912 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000913 // Check for the special-case of initializing an array with a string.
914 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000915 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
916 SemaRef.Context)) {
917 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000918 // We place the string literal directly into the resulting
919 // initializer list. This is the only place where the structure
920 // of the structured initializer list doesn't match exactly,
921 // because doing so would involve allocating one character
922 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000923 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000924 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000925 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000926 return;
927 }
928 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000929 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000930 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000931 // Check for VLAs; in standard C it would be possible to check this
932 // earlier, but I don't know where clang accepts VLAs (gcc accepts
933 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000934 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000935 diag::err_variable_object_no_init)
936 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000937 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000938 ++Index;
939 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000940 return;
941 }
942
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000943 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000944 llvm::APSInt maxElements(elementIndex.getBitWidth(),
945 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000946 bool maxElementsKnown = false;
947 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000948 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000949 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000950 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000951 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000952 maxElementsKnown = true;
953 }
954
Chris Lattnerb0912a52009-02-24 22:50:46 +0000955 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000956 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000957 while (Index < IList->getNumInits()) {
958 Expr *Init = IList->getInit(Index);
959 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000960 // If we're not the subobject that matches up with the '{' for
961 // the designator, we shouldn't be handling the
962 // designator. Return immediately.
963 if (!SubobjectIsDesignatorContext)
964 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000965
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000966 // Handle this designated initializer. elementIndex will be
967 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000968 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000969 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000970 StructuredList, StructuredIndex, true,
971 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000972 hadError = true;
973 continue;
974 }
975
Douglas Gregor033d1252009-01-23 16:54:12 +0000976 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
977 maxElements.extend(elementIndex.getBitWidth());
978 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
979 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000980 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000981
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000982 // If the array is of incomplete type, keep track of the number of
983 // elements in the initializer.
984 if (!maxElementsKnown && elementIndex > maxElements)
985 maxElements = elementIndex;
986
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000987 continue;
988 }
989
990 // If we know the maximum number of elements, and we've already
991 // hit it, stop consuming elements in the initializer list.
992 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000993 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000994
Anders Carlsson6cabf312010-01-23 23:23:01 +0000995 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000996 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000997 Entity);
998 // Check this element.
999 CheckSubElementType(ElementEntity, IList, elementType, Index,
1000 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001001 ++elementIndex;
1002
1003 // If the array is of incomplete type, keep track of the number of
1004 // elements in the initializer.
1005 if (!maxElementsKnown && elementIndex > maxElements)
1006 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001007 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001008 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001009 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001010 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001011 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001012 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001013 // Sizing an array implicitly to zero is not allowed by ISO C,
1014 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001015 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001016 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001017 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001018
Mike Stump11289f42009-09-09 15:08:12 +00001019 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001020 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001021 }
1022}
1023
Anders Carlsson6cabf312010-01-23 23:23:01 +00001024void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001025 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001026 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001027 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001028 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001029 unsigned &Index,
1030 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001031 unsigned &StructuredIndex,
1032 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001033 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001034
Eli Friedman23a9e312008-05-19 19:16:24 +00001035 // If the record is invalid, some of it's members are invalid. To avoid
1036 // confusion, we forgo checking the intializer for the entire record.
1037 if (structDecl->isInvalidDecl()) {
1038 hadError = true;
1039 return;
Mike Stump11289f42009-09-09 15:08:12 +00001040 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001041
1042 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1043 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001044 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001045 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001046 Field != FieldEnd; ++Field) {
1047 if (Field->getDeclName()) {
1048 StructuredList->setInitializedFieldInUnion(*Field);
1049 break;
1050 }
1051 }
1052 return;
1053 }
1054
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001055 // If structDecl is a forward declaration, this loop won't do
1056 // anything except look at designated initializers; That's okay,
1057 // because an error should get printed out elsewhere. It might be
1058 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001060 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001061 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001062 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001063 while (Index < IList->getNumInits()) {
1064 Expr *Init = IList->getInit(Index);
1065
1066 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001067 // If we're not the subobject that matches up with the '{' for
1068 // the designator, we shouldn't be handling the
1069 // designator. Return immediately.
1070 if (!SubobjectIsDesignatorContext)
1071 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001072
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001073 // Handle this designated initializer. Field will be updated to
1074 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001075 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001076 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001077 StructuredList, StructuredIndex,
1078 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001079 hadError = true;
1080
Douglas Gregora9add4e2009-02-12 19:00:39 +00001081 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001082
1083 // Disable check for missing fields when designators are used.
1084 // This matches gcc behaviour.
1085 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001086 continue;
1087 }
1088
1089 if (Field == FieldEnd) {
1090 // We've run out of fields. We're done.
1091 break;
1092 }
1093
Douglas Gregora9add4e2009-02-12 19:00:39 +00001094 // We've already initialized a member of a union. We're done.
1095 if (InitializedSomething && DeclType->isUnionType())
1096 break;
1097
Douglas Gregor91f84212008-12-11 16:49:14 +00001098 // If we've hit the flexible array member at the end, we're done.
1099 if (Field->getType()->isIncompleteArrayType())
1100 break;
1101
Douglas Gregor51695702009-01-29 16:53:55 +00001102 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001103 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001104 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001105 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001106 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001107
Anders Carlsson6cabf312010-01-23 23:23:01 +00001108 InitializedEntity MemberEntity =
1109 InitializedEntity::InitializeMember(*Field, &Entity);
1110 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1111 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001112 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001113
1114 if (DeclType->isUnionType()) {
1115 // Initialize the first field within the union.
1116 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001117 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001118
1119 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001120 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001121
John McCalle40b58e2010-03-11 19:32:38 +00001122 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001123 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001124 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1125 // It is possible we have one or more unnamed bitfields remaining.
1126 // Find first (if any) named field and emit warning.
1127 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1128 it != end; ++it) {
1129 if (!it->isUnnamedBitfield()) {
1130 SemaRef.Diag(IList->getSourceRange().getEnd(),
1131 diag::warn_missing_field_initializers) << it->getName();
1132 break;
1133 }
1134 }
1135 }
1136
Mike Stump11289f42009-09-09 15:08:12 +00001137 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001138 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001139 return;
1140
1141 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001142 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001143 (!isa<InitListExpr>(IList->getInit(Index)) ||
1144 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001145 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001146 diag::err_flexible_array_init_nonempty)
1147 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001148 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001149 << *Field;
1150 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001151 ++Index;
1152 return;
1153 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001154 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001155 diag::ext_flexible_array_init)
1156 << IList->getInit(Index)->getSourceRange().getBegin();
1157 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1158 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001159 }
1160
Anders Carlsson6cabf312010-01-23 23:23:01 +00001161 InitializedEntity MemberEntity =
1162 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001163
Anders Carlsson6cabf312010-01-23 23:23:01 +00001164 if (isa<InitListExpr>(IList->getInit(Index)))
1165 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1166 StructuredList, StructuredIndex);
1167 else
1168 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001169 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001170}
Steve Narofff8ecff22008-05-01 22:18:59 +00001171
Douglas Gregord5846a12009-04-15 06:41:24 +00001172/// \brief Expand a field designator that refers to a member of an
1173/// anonymous struct or union into a series of field designators that
1174/// refers to the field within the appropriate subobject.
1175///
1176/// Field/FieldIndex will be updated to point to the (new)
1177/// currently-designated field.
1178static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001179 DesignatedInitExpr *DIE,
1180 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001181 FieldDecl *Field,
1182 RecordDecl::field_iterator &FieldIter,
1183 unsigned &FieldIndex) {
1184 typedef DesignatedInitExpr::Designator Designator;
1185
1186 // Build the path from the current object to the member of the
1187 // anonymous struct/union (backwards).
1188 llvm::SmallVector<FieldDecl *, 4> Path;
1189 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001190
Douglas Gregord5846a12009-04-15 06:41:24 +00001191 // Build the replacement designators.
1192 llvm::SmallVector<Designator, 4> Replacements;
1193 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1194 FI = Path.rbegin(), FIEnd = Path.rend();
1195 FI != FIEnd; ++FI) {
1196 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001197 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001198 DIE->getDesignator(DesigIdx)->getDotLoc(),
1199 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1200 else
1201 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1202 SourceLocation()));
1203 Replacements.back().setField(*FI);
1204 }
1205
1206 // Expand the current designator into the set of replacement
1207 // designators, so we have a full subobject path down to where the
1208 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001209 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001210 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001211
Douglas Gregord5846a12009-04-15 06:41:24 +00001212 // Update FieldIter/FieldIndex;
1213 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001214 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001215 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001216 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001217 FieldIter != FEnd; ++FieldIter) {
1218 if (FieldIter->isUnnamedBitfield())
1219 continue;
1220
1221 if (*FieldIter == Path.back())
1222 return;
1223
1224 ++FieldIndex;
1225 }
1226
1227 assert(false && "Unable to find anonymous struct/union field");
1228}
1229
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001230/// @brief Check the well-formedness of a C99 designated initializer.
1231///
1232/// Determines whether the designated initializer @p DIE, which
1233/// resides at the given @p Index within the initializer list @p
1234/// IList, is well-formed for a current object of type @p DeclType
1235/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001236/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001237/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001238///
1239/// @param IList The initializer list in which this designated
1240/// initializer occurs.
1241///
Douglas Gregora5324162009-04-15 04:56:10 +00001242/// @param DIE The designated initializer expression.
1243///
1244/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001245///
1246/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1247/// into which the designation in @p DIE should refer.
1248///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001249/// @param NextField If non-NULL and the first designator in @p DIE is
1250/// a field, this will be set to the field declaration corresponding
1251/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001252///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001253/// @param NextElementIndex If non-NULL and the first designator in @p
1254/// DIE is an array designator or GNU array-range designator, this
1255/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001256///
1257/// @param Index Index into @p IList where the designated initializer
1258/// @p DIE occurs.
1259///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001260/// @param StructuredList The initializer list expression that
1261/// describes all of the subobject initializers in the order they'll
1262/// actually be initialized.
1263///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001264/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001265bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001266InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001267 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001268 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001269 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001270 QualType &CurrentObjectType,
1271 RecordDecl::field_iterator *NextField,
1272 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001273 unsigned &Index,
1274 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001275 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001276 bool FinishSubobjectInit,
1277 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001278 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001279 // Check the actual initialization for the designated object type.
1280 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001281
1282 // Temporarily remove the designator expression from the
1283 // initializer list that the child calls see, so that we don't try
1284 // to re-process the designator.
1285 unsigned OldIndex = Index;
1286 IList->setInit(OldIndex, DIE->getInit());
1287
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001288 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001289 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001290
1291 // Restore the designated initializer expression in the syntactic
1292 // form of the initializer list.
1293 if (IList->getInit(OldIndex) != DIE->getInit())
1294 DIE->setInit(IList->getInit(OldIndex));
1295 IList->setInit(OldIndex, DIE);
1296
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001297 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001298 }
1299
Douglas Gregora5324162009-04-15 04:56:10 +00001300 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001301 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001302 "Need a non-designated initializer list to start from");
1303
Douglas Gregora5324162009-04-15 04:56:10 +00001304 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001305 // Determine the structural initializer list that corresponds to the
1306 // current subobject.
1307 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001308 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001309 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001310 SourceRange(D->getStartLocation(),
1311 DIE->getSourceRange().getEnd()));
1312 assert(StructuredList && "Expected a structured initializer list");
1313
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 if (D->isFieldDesignator()) {
1315 // C99 6.7.8p7:
1316 //
1317 // If a designator has the form
1318 //
1319 // . identifier
1320 //
1321 // then the current object (defined below) shall have
1322 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001323 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001324 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001325 if (!RT) {
1326 SourceLocation Loc = D->getDotLoc();
1327 if (Loc.isInvalid())
1328 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001329 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1330 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001331 ++Index;
1332 return true;
1333 }
1334
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001335 // Note: we perform a linear search of the fields here, despite
1336 // the fact that we have a faster lookup method, because we always
1337 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001338 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001339 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001340 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001341 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001342 Field = RT->getDecl()->field_begin(),
1343 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001344 for (; Field != FieldEnd; ++Field) {
1345 if (Field->isUnnamedBitfield())
1346 continue;
1347
Douglas Gregord5846a12009-04-15 06:41:24 +00001348 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001349 break;
1350
1351 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001352 }
1353
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001354 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001355 // There was no normal field in the struct with the designated
1356 // name. Perform another lookup for this name, which may find
1357 // something that we can't designate (e.g., a member function),
1358 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001359 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001360 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001361 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001362 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001363 // Name lookup didn't find anything. Determine whether this
1364 // was a typo for another field name.
1365 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1366 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001367 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1368 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001369 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1370 ReplacementField->getDeclContext()->getLookupContext()
1371 ->Equals(RT->getDecl())) {
1372 SemaRef.Diag(D->getFieldLoc(),
1373 diag::err_field_designator_unknown_suggest)
1374 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001375 << FixItHint::CreateReplacement(D->getFieldLoc(),
1376 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001377 SemaRef.Diag(ReplacementField->getLocation(),
1378 diag::note_previous_decl)
1379 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001380 } else {
1381 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1382 << FieldName << CurrentObjectType;
1383 ++Index;
1384 return true;
1385 }
1386 } else if (!KnownField) {
1387 // Determine whether we found a field at all.
1388 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1389 }
1390
1391 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001392 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001393 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001395 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001396 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001397 ++Index;
1398 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001399 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001400
1401 if (!KnownField &&
1402 cast<RecordDecl>((ReplacementField)->getDeclContext())
1403 ->isAnonymousStructOrUnion()) {
1404 // Handle an field designator that refers to a member of an
1405 // anonymous struct or union.
1406 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1407 ReplacementField,
1408 Field, FieldIndex);
1409 D = DIE->getDesignator(DesigIdx);
1410 } else if (!KnownField) {
1411 // The replacement field comes from typo correction; find it
1412 // in the list of fields.
1413 FieldIndex = 0;
1414 Field = RT->getDecl()->field_begin();
1415 for (; Field != FieldEnd; ++Field) {
1416 if (Field->isUnnamedBitfield())
1417 continue;
1418
1419 if (ReplacementField == *Field ||
1420 Field->getIdentifier() == ReplacementField->getIdentifier())
1421 break;
1422
1423 ++FieldIndex;
1424 }
1425 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001426 } else if (!KnownField &&
1427 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001428 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001429 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1430 Field, FieldIndex);
1431 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001432 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001433
1434 // All of the fields of a union are located at the same place in
1435 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001436 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001437 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001438 StructuredList->setInitializedFieldInUnion(*Field);
1439 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001440
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001441 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001442 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001443
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001444 // Make sure that our non-designated initializer list has space
1445 // for a subobject corresponding to this field.
1446 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001447 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001448
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001449 // This designator names a flexible array member.
1450 if (Field->getType()->isIncompleteArrayType()) {
1451 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001452 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001453 // We can't designate an object within the flexible array
1454 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001455 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001456 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001457 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001458 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001459 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001461 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001462 << *Field;
1463 Invalid = true;
1464 }
1465
1466 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1467 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001468 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001469 diag::err_flexible_array_init_needs_braces)
1470 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001471 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001472 << *Field;
1473 Invalid = true;
1474 }
1475
1476 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001477 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001478 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001479 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 diag::err_flexible_array_init_nonempty)
1481 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001482 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001483 << *Field;
1484 Invalid = true;
1485 }
1486
1487 if (Invalid) {
1488 ++Index;
1489 return true;
1490 }
1491
1492 // Initialize the array.
1493 bool prevHadError = hadError;
1494 unsigned newStructuredIndex = FieldIndex;
1495 unsigned OldIndex = Index;
1496 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001497
1498 InitializedEntity MemberEntity =
1499 InitializedEntity::InitializeMember(*Field, &Entity);
1500 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001501 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001502
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001503 IList->setInit(OldIndex, DIE);
1504 if (hadError && !prevHadError) {
1505 ++Field;
1506 ++FieldIndex;
1507 if (NextField)
1508 *NextField = Field;
1509 StructuredIndex = FieldIndex;
1510 return true;
1511 }
1512 } else {
1513 // Recurse to check later designated subobjects.
1514 QualType FieldType = (*Field)->getType();
1515 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001516
1517 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001518 InitializedEntity::InitializeMember(*Field, &Entity);
1519 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001520 FieldType, 0, 0, Index,
1521 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001522 true, false))
1523 return true;
1524 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001525
1526 // Find the position of the next field to be initialized in this
1527 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001528 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001529 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001530
1531 // If this the first designator, our caller will continue checking
1532 // the rest of this struct/class/union subobject.
1533 if (IsFirstDesignator) {
1534 if (NextField)
1535 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001536 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001537 return false;
1538 }
1539
Douglas Gregor17bd0942009-01-28 23:36:17 +00001540 if (!FinishSubobjectInit)
1541 return false;
1542
Douglas Gregord5846a12009-04-15 06:41:24 +00001543 // We've already initialized something in the union; we're done.
1544 if (RT->getDecl()->isUnion())
1545 return hadError;
1546
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001547 // Check the remaining fields within this class/struct/union subobject.
1548 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001549
Anders Carlsson6cabf312010-01-23 23:23:01 +00001550 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001551 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001552 return hadError && !prevHadError;
1553 }
1554
1555 // C99 6.7.8p6:
1556 //
1557 // If a designator has the form
1558 //
1559 // [ constant-expression ]
1560 //
1561 // then the current object (defined below) shall have array
1562 // type and the expression shall be an integer constant
1563 // expression. If the array is of unknown size, any
1564 // nonnegative value is valid.
1565 //
1566 // Additionally, cope with the GNU extension that permits
1567 // designators of the form
1568 //
1569 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001570 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001572 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573 << CurrentObjectType;
1574 ++Index;
1575 return true;
1576 }
1577
1578 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001579 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1580 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001581 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001582 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001583 DesignatedEndIndex = DesignatedStartIndex;
1584 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001585 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001586
Mike Stump11289f42009-09-09 15:08:12 +00001587
1588 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001589 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001590 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001591 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001592 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001593
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001594 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001595 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001596 }
1597
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001598 if (isa<ConstantArrayType>(AT)) {
1599 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001600 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1601 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1602 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1603 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1604 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001605 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001607 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001608 << IndexExpr->getSourceRange();
1609 ++Index;
1610 return true;
1611 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001612 } else {
1613 // Make sure the bit-widths and signedness match.
1614 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1615 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001616 else if (DesignatedStartIndex.getBitWidth() <
1617 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001618 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1619 DesignatedStartIndex.setIsUnsigned(true);
1620 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001623 // Make sure that our non-designated initializer list has space
1624 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001625 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001626 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001628
Douglas Gregor17bd0942009-01-28 23:36:17 +00001629 // Repeatedly perform subobject initializations in the range
1630 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001631
Douglas Gregor17bd0942009-01-28 23:36:17 +00001632 // Move to the next designator
1633 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1634 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001635
1636 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001637 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001638
Douglas Gregor17bd0942009-01-28 23:36:17 +00001639 while (DesignatedStartIndex <= DesignatedEndIndex) {
1640 // Recurse to check later designated subobjects.
1641 QualType ElementType = AT->getElementType();
1642 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001643
1644 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001645 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001646 ElementType, 0, 0, Index,
1647 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001648 (DesignatedStartIndex == DesignatedEndIndex),
1649 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001650 return true;
1651
1652 // Move to the next index in the array that we'll be initializing.
1653 ++DesignatedStartIndex;
1654 ElementIndex = DesignatedStartIndex.getZExtValue();
1655 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001656
1657 // If this the first designator, our caller will continue checking
1658 // the rest of this array subobject.
1659 if (IsFirstDesignator) {
1660 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001661 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001663 return false;
1664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 if (!FinishSubobjectInit)
1667 return false;
1668
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001669 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001670 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001671 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001672 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001673 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001674 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001675}
1676
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001677// Get the structured initializer list for a subobject of type
1678// @p CurrentObjectType.
1679InitListExpr *
1680InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1681 QualType CurrentObjectType,
1682 InitListExpr *StructuredList,
1683 unsigned StructuredIndex,
1684 SourceRange InitRange) {
1685 Expr *ExistingInit = 0;
1686 if (!StructuredList)
1687 ExistingInit = SyntacticToSemantic[IList];
1688 else if (StructuredIndex < StructuredList->getNumInits())
1689 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001690
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1692 return Result;
1693
1694 if (ExistingInit) {
1695 // We are creating an initializer list that initializes the
1696 // subobjects of the current object, but there was already an
1697 // initialization that completely initialized the current
1698 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001699 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001700 // struct X { int a, b; };
1701 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001702 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001703 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1704 // designated initializer re-initializes the whole
1705 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001706 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001707 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001708 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001709 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001711 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001712 << ExistingInit->getSourceRange();
1713 }
1714
Mike Stump11289f42009-09-09 15:08:12 +00001715 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001716 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1717 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001718 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001719
Douglas Gregora8a089b2010-07-13 18:40:04 +00001720 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001721
Douglas Gregor6d00c992009-03-20 23:58:33 +00001722 // Pre-allocate storage for the structured initializer list.
1723 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001724 unsigned NumInits = 0;
1725 if (!StructuredList)
1726 NumInits = IList->getNumInits();
1727 else if (Index < IList->getNumInits()) {
1728 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1729 NumInits = SubList->getNumInits();
1730 }
1731
Mike Stump11289f42009-09-09 15:08:12 +00001732 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001733 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1734 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1735 NumElements = CAType->getSize().getZExtValue();
1736 // Simple heuristic so that we don't allocate a very large
1737 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001738 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001739 NumElements = 0;
1740 }
John McCall9dd450b2009-09-21 23:43:11 +00001741 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001742 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001743 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001744 RecordDecl *RDecl = RType->getDecl();
1745 if (RDecl->isUnion())
1746 NumElements = 1;
1747 else
Mike Stump11289f42009-09-09 15:08:12 +00001748 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001749 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001750 }
1751
Douglas Gregor221c9a52009-03-21 18:13:52 +00001752 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001753 NumElements = IList->getNumInits();
1754
Ted Kremenekac034612010-04-13 23:39:13 +00001755 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001756
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001757 // Link this new initializer list into the structured initializer
1758 // lists.
1759 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001760 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001761 else {
1762 Result->setSyntacticForm(IList);
1763 SyntacticToSemantic[IList] = Result;
1764 }
1765
1766 return Result;
1767}
1768
1769/// Update the initializer at index @p StructuredIndex within the
1770/// structured initializer list to the value @p expr.
1771void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1772 unsigned &StructuredIndex,
1773 Expr *expr) {
1774 // No structured initializer list to update
1775 if (!StructuredList)
1776 return;
1777
Ted Kremenekac034612010-04-13 23:39:13 +00001778 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1779 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001781 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001782 diag::warn_initializer_overrides)
1783 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001784 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001785 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001786 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001787 << PrevInit->getSourceRange();
1788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001790 ++StructuredIndex;
1791}
1792
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001793/// Check that the given Index expression is a valid array designator
1794/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001795/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001796/// and produces a reasonable diagnostic if there is a
1797/// failure. Returns true if there was an error, false otherwise. If
1798/// everything went okay, Value will receive the value of the constant
1799/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001800static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001801CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001802 SourceLocation Loc = Index->getSourceRange().getBegin();
1803
1804 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001805 if (S.VerifyIntegerConstantExpression(Index, &Value))
1806 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001807
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001808 if (Value.isSigned() && Value.isNegative())
1809 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001810 << Value.toString(10) << Index->getSourceRange();
1811
Douglas Gregor51650d32009-01-23 21:04:18 +00001812 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001813 return false;
1814}
1815
John McCalldadc5752010-08-24 06:29:42 +00001816ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001817 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001818 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001819 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001820 typedef DesignatedInitExpr::Designator ASTDesignator;
1821
1822 bool Invalid = false;
1823 llvm::SmallVector<ASTDesignator, 32> Designators;
1824 llvm::SmallVector<Expr *, 32> InitExpressions;
1825
1826 // Build designators and check array designator expressions.
1827 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1828 const Designator &D = Desig.getDesignator(Idx);
1829 switch (D.getKind()) {
1830 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001831 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001832 D.getFieldLoc()));
1833 break;
1834
1835 case Designator::ArrayDesignator: {
1836 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1837 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001838 if (!Index->isTypeDependent() &&
1839 !Index->isValueDependent() &&
1840 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001841 Invalid = true;
1842 else {
1843 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001844 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001845 D.getRBracketLoc()));
1846 InitExpressions.push_back(Index);
1847 }
1848 break;
1849 }
1850
1851 case Designator::ArrayRangeDesignator: {
1852 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1853 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1854 llvm::APSInt StartValue;
1855 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001856 bool StartDependent = StartIndex->isTypeDependent() ||
1857 StartIndex->isValueDependent();
1858 bool EndDependent = EndIndex->isTypeDependent() ||
1859 EndIndex->isValueDependent();
1860 if ((!StartDependent &&
1861 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1862 (!EndDependent &&
1863 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001864 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001865 else {
1866 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001867 if (StartDependent || EndDependent) {
1868 // Nothing to compute.
1869 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001870 EndValue.extend(StartValue.getBitWidth());
1871 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1872 StartValue.extend(EndValue.getBitWidth());
1873
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001874 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001875 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001876 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001877 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1878 Invalid = true;
1879 } else {
1880 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001881 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001882 D.getEllipsisLoc(),
1883 D.getRBracketLoc()));
1884 InitExpressions.push_back(StartIndex);
1885 InitExpressions.push_back(EndIndex);
1886 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001887 }
1888 break;
1889 }
1890 }
1891 }
1892
1893 if (Invalid || Init.isInvalid())
1894 return ExprError();
1895
1896 // Clear out the expressions within the designation.
1897 Desig.ClearExprs(*this);
1898
1899 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001900 = DesignatedInitExpr::Create(Context,
1901 Designators.data(), Designators.size(),
1902 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001903 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001904 return Owned(DIE);
1905}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001906
Douglas Gregor723796a2009-12-16 06:35:08 +00001907bool Sema::CheckInitList(const InitializedEntity &Entity,
1908 InitListExpr *&InitList, QualType &DeclType) {
1909 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001910 if (!CheckInitList.HadError())
1911 InitList = CheckInitList.getFullyStructuredList();
1912
1913 return CheckInitList.HadError();
1914}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001915
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001916//===----------------------------------------------------------------------===//
1917// Initialization entity
1918//===----------------------------------------------------------------------===//
1919
Douglas Gregor723796a2009-12-16 06:35:08 +00001920InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1921 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001922 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001923{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001924 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1925 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001926 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001927 } else {
1928 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001929 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001930 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001931}
1932
1933InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001934 CXXBaseSpecifier *Base,
1935 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001936{
1937 InitializedEntity Result;
1938 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001939 Result.Base = reinterpret_cast<uintptr_t>(Base);
1940 if (IsInheritedVirtualBase)
1941 Result.Base |= 0x01;
1942
Douglas Gregor1b303932009-12-22 15:35:07 +00001943 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001944 return Result;
1945}
1946
Douglas Gregor85dabae2009-12-16 01:38:02 +00001947DeclarationName InitializedEntity::getName() const {
1948 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001949 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001950 if (!VariableOrMember)
1951 return DeclarationName();
1952 // Fall through
1953
1954 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001955 case EK_Member:
1956 return VariableOrMember->getDeclName();
1957
1958 case EK_Result:
1959 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001960 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001961 case EK_Temporary:
1962 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001963 case EK_ArrayElement:
1964 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001965 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001966 return DeclarationName();
1967 }
1968
1969 // Silence GCC warning
1970 return DeclarationName();
1971}
1972
Douglas Gregora4b592a2009-12-19 03:01:41 +00001973DeclaratorDecl *InitializedEntity::getDecl() const {
1974 switch (getKind()) {
1975 case EK_Variable:
1976 case EK_Parameter:
1977 case EK_Member:
1978 return VariableOrMember;
1979
1980 case EK_Result:
1981 case EK_Exception:
1982 case EK_New:
1983 case EK_Temporary:
1984 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001985 case EK_ArrayElement:
1986 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001987 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001988 return 0;
1989 }
1990
1991 // Silence GCC warning
1992 return 0;
1993}
1994
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001995bool InitializedEntity::allowsNRVO() const {
1996 switch (getKind()) {
1997 case EK_Result:
1998 case EK_Exception:
1999 return LocAndNRVO.NRVO;
2000
2001 case EK_Variable:
2002 case EK_Parameter:
2003 case EK_Member:
2004 case EK_New:
2005 case EK_Temporary:
2006 case EK_Base:
2007 case EK_ArrayElement:
2008 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002009 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002010 break;
2011 }
2012
2013 return false;
2014}
2015
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002016//===----------------------------------------------------------------------===//
2017// Initialization sequence
2018//===----------------------------------------------------------------------===//
2019
2020void InitializationSequence::Step::Destroy() {
2021 switch (Kind) {
2022 case SK_ResolveAddressOfOverloadedFunction:
2023 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002024 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002025 case SK_CastDerivedToBaseLValue:
2026 case SK_BindReference:
2027 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002028 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002029 case SK_UserConversion:
2030 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002031 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002032 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002033 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002034 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002035 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002036 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002037 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002038 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002039 break;
2040
2041 case SK_ConversionSequence:
2042 delete ICS;
2043 }
2044}
2045
Douglas Gregor838fcc32010-03-26 20:14:36 +00002046bool InitializationSequence::isDirectReferenceBinding() const {
2047 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2048}
2049
2050bool InitializationSequence::isAmbiguous() const {
2051 if (getKind() != FailedSequence)
2052 return false;
2053
2054 switch (getFailureKind()) {
2055 case FK_TooManyInitsForReference:
2056 case FK_ArrayNeedsInitList:
2057 case FK_ArrayNeedsInitListOrStringLiteral:
2058 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2059 case FK_NonConstLValueReferenceBindingToTemporary:
2060 case FK_NonConstLValueReferenceBindingToUnrelated:
2061 case FK_RValueReferenceBindingToLValue:
2062 case FK_ReferenceInitDropsQualifiers:
2063 case FK_ReferenceInitFailed:
2064 case FK_ConversionFailed:
2065 case FK_TooManyInitsForScalar:
2066 case FK_ReferenceBindingToInitList:
2067 case FK_InitListBadDestinationType:
2068 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002069 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002070 return false;
2071
2072 case FK_ReferenceInitOverloadFailed:
2073 case FK_UserConversionOverloadFailed:
2074 case FK_ConstructorOverloadFailed:
2075 return FailedOverloadResult == OR_Ambiguous;
2076 }
2077
2078 return false;
2079}
2080
Douglas Gregorb33eed02010-04-16 22:09:46 +00002081bool InitializationSequence::isConstructorInitialization() const {
2082 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2083}
2084
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002085void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002086 FunctionDecl *Function,
2087 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002088 Step S;
2089 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2090 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002091 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002092 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002093 Steps.push_back(S);
2094}
2095
2096void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002097 ImplicitCastExpr::ResultCategory Category) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002098 Step S;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002099 switch (Category) {
2100 case ImplicitCastExpr::RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2101 case ImplicitCastExpr::XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2102 case ImplicitCastExpr::LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2103 default: llvm_unreachable("No such category");
2104 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002105 S.Type = BaseType;
2106 Steps.push_back(S);
2107}
2108
2109void InitializationSequence::AddReferenceBindingStep(QualType T,
2110 bool BindingTemporary) {
2111 Step S;
2112 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2113 S.Type = T;
2114 Steps.push_back(S);
2115}
2116
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002117void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2118 Step S;
2119 S.Kind = SK_ExtraneousCopyToTemporary;
2120 S.Type = T;
2121 Steps.push_back(S);
2122}
2123
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002124void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002125 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002126 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002127 Step S;
2128 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002129 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002130 S.Function.Function = Function;
2131 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002132 Steps.push_back(S);
2133}
2134
2135void InitializationSequence::AddQualificationConversionStep(QualType Ty,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002136 ImplicitCastExpr::ResultCategory Category) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002137 Step S;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002138 switch (Category) {
2139 case ImplicitCastExpr::RValue:
2140 S.Kind = SK_QualificationConversionRValue;
2141 break;
2142 case ImplicitCastExpr::XValue:
2143 S.Kind = SK_QualificationConversionXValue;
2144 break;
2145 case ImplicitCastExpr::LValue:
2146 S.Kind = SK_QualificationConversionLValue;
2147 break;
2148 default: llvm_unreachable("No such category");
2149 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002150 S.Type = Ty;
2151 Steps.push_back(S);
2152}
2153
2154void InitializationSequence::AddConversionSequenceStep(
2155 const ImplicitConversionSequence &ICS,
2156 QualType T) {
2157 Step S;
2158 S.Kind = SK_ConversionSequence;
2159 S.Type = T;
2160 S.ICS = new ImplicitConversionSequence(ICS);
2161 Steps.push_back(S);
2162}
2163
Douglas Gregor51e77d52009-12-10 17:56:55 +00002164void InitializationSequence::AddListInitializationStep(QualType T) {
2165 Step S;
2166 S.Kind = SK_ListInitialization;
2167 S.Type = T;
2168 Steps.push_back(S);
2169}
2170
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002171void
2172InitializationSequence::AddConstructorInitializationStep(
2173 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002174 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002175 QualType T) {
2176 Step S;
2177 S.Kind = SK_ConstructorInitialization;
2178 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002179 S.Function.Function = Constructor;
2180 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002181 Steps.push_back(S);
2182}
2183
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002184void InitializationSequence::AddZeroInitializationStep(QualType T) {
2185 Step S;
2186 S.Kind = SK_ZeroInitialization;
2187 S.Type = T;
2188 Steps.push_back(S);
2189}
2190
Douglas Gregore1314a62009-12-18 05:02:21 +00002191void InitializationSequence::AddCAssignmentStep(QualType T) {
2192 Step S;
2193 S.Kind = SK_CAssignment;
2194 S.Type = T;
2195 Steps.push_back(S);
2196}
2197
Eli Friedman78275202009-12-19 08:11:05 +00002198void InitializationSequence::AddStringInitStep(QualType T) {
2199 Step S;
2200 S.Kind = SK_StringInit;
2201 S.Type = T;
2202 Steps.push_back(S);
2203}
2204
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002205void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2206 Step S;
2207 S.Kind = SK_ObjCObjectConversion;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2213 OverloadingResult Result) {
2214 SequenceKind = FailedSequence;
2215 this->Failure = Failure;
2216 this->FailedOverloadResult = Result;
2217}
2218
2219//===----------------------------------------------------------------------===//
2220// Attempt initialization
2221//===----------------------------------------------------------------------===//
2222
2223/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002224static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002225 const InitializedEntity &Entity,
2226 const InitializationKind &Kind,
2227 InitListExpr *InitList,
2228 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002229 // FIXME: We only perform rudimentary checking of list
2230 // initializations at this point, then assume that any list
2231 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002232 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002233 // do all of the necessary checking. C++0x initializer lists will
2234 // force us to perform more checking here.
2235 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2236
Douglas Gregor1b303932009-12-22 15:35:07 +00002237 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002238
2239 // C++ [dcl.init]p13:
2240 // If T is a scalar type, then a declaration of the form
2241 //
2242 // T x = { a };
2243 //
2244 // is equivalent to
2245 //
2246 // T x = a;
2247 if (DestType->isScalarType()) {
2248 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2249 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2250 return;
2251 }
2252
2253 // Assume scalar initialization from a single value works.
2254 } else if (DestType->isAggregateType()) {
2255 // Assume aggregate initialization works.
2256 } else if (DestType->isVectorType()) {
2257 // Assume vector initialization works.
2258 } else if (DestType->isReferenceType()) {
2259 // FIXME: C++0x defines behavior for this.
2260 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2261 return;
2262 } else if (DestType->isRecordType()) {
2263 // FIXME: C++0x defines behavior for this
2264 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2265 }
2266
2267 // Add a general "list initialization" step.
2268 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002269}
2270
2271/// \brief Try a reference initialization that involves calling a conversion
2272/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002273static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2274 const InitializedEntity &Entity,
2275 const InitializationKind &Kind,
2276 Expr *Initializer,
2277 bool AllowRValues,
2278 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002279 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002280 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2281 QualType T1 = cv1T1.getUnqualifiedType();
2282 QualType cv2T2 = Initializer->getType();
2283 QualType T2 = cv2T2.getUnqualifiedType();
2284
2285 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002286 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002287 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002288 T1, T2, DerivedToBase,
2289 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002290 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002291 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002292 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002293
2294 // Build the candidate set directly in the initialization sequence
2295 // structure, so that it will persist if we fail.
2296 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2297 CandidateSet.clear();
2298
2299 // Determine whether we are allowed to call explicit constructors or
2300 // explicit conversion operators.
2301 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2302
2303 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002304 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2305 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002306 // The type we're converting to is a class type. Enumerate its constructors
2307 // to see if there is a suitable conversion.
2308 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002309
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002311 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002312 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002313 NamedDecl *D = *Con;
2314 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002316 // Find the constructor (which may be a template).
2317 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002318 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002319 if (ConstructorTmpl)
2320 Constructor = cast<CXXConstructorDecl>(
2321 ConstructorTmpl->getTemplatedDecl());
2322 else
John McCalla0296f72010-03-19 07:35:19 +00002323 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002324
2325 if (!Constructor->isInvalidDecl() &&
2326 Constructor->isConvertingConstructor(AllowExplicit)) {
2327 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002328 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002329 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002330 &Initializer, 1, CandidateSet);
2331 else
John McCalla0296f72010-03-19 07:35:19 +00002332 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002333 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002334 }
2335 }
2336 }
John McCall3696dcb2010-08-17 07:23:57 +00002337 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2338 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002339
Douglas Gregor496e8b342010-05-07 19:42:26 +00002340 const RecordType *T2RecordType = 0;
2341 if ((T2RecordType = T2->getAs<RecordType>()) &&
2342 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002343 // The type we're converting from is a class type, enumerate its conversion
2344 // functions.
2345 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2346
2347 // Determine the type we are converting to. If we are allowed to
2348 // convert to an rvalue, take the type that the destination type
2349 // refers to.
2350 QualType ToType = AllowRValues? cv1T1 : DestType;
2351
John McCallad371252010-01-20 00:46:10 +00002352 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002354 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2355 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002356 NamedDecl *D = *I;
2357 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2358 if (isa<UsingShadowDecl>(D))
2359 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2360
2361 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2362 CXXConversionDecl *Conv;
2363 if (ConvTemplate)
2364 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2365 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002366 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002367
2368 // If the conversion function doesn't return a reference type,
2369 // it can't be considered for this conversion unless we're allowed to
2370 // consider rvalues.
2371 // FIXME: Do we need to make sure that we only consider conversion
2372 // candidates with reference-compatible results? That might be needed to
2373 // break recursion.
2374 if ((AllowExplicit || !Conv->isExplicit()) &&
2375 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2376 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002377 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002378 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002379 ToType, CandidateSet);
2380 else
John McCalla0296f72010-03-19 07:35:19 +00002381 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002382 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383 }
2384 }
2385 }
John McCall3696dcb2010-08-17 07:23:57 +00002386 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2387 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002388
2389 SourceLocation DeclLoc = Initializer->getLocStart();
2390
2391 // Perform overload resolution. If it fails, return the failed result.
2392 OverloadCandidateSet::iterator Best;
2393 if (OverloadingResult Result
2394 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2395 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002396
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002398
2399 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 if (isa<CXXConversionDecl>(Function))
2401 T2 = Function->getResultType();
2402 else
2403 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002404
2405 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002406 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002407 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002408
2409 // Determine whether we need to perform derived-to-base or
2410 // cv-qualification adjustments.
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002411 ImplicitCastExpr::ResultCategory Category = ImplicitCastExpr::RValue;
2412 if (T2->isLValueReferenceType())
2413 Category = ImplicitCastExpr::LValue;
2414 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
2415 Category = RRef->getPointeeType()->isFunctionType() ?
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002416 ImplicitCastExpr::LValue : ImplicitCastExpr::XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002419 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002421 = S.CompareReferenceRelationship(DeclLoc, T1,
2422 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002423 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002424 if (NewRefRelationship == Sema::Ref_Incompatible) {
2425 // If the type we've converted to is not reference-related to the
2426 // type we're looking for, then there is another conversion step
2427 // we need to perform to produce a temporary of the right type
2428 // that we'll be binding to.
2429 ImplicitConversionSequence ICS;
2430 ICS.setStandard();
2431 ICS.Standard = Best->FinalConversion;
2432 T2 = ICS.Standard.getToType(2);
2433 Sequence.AddConversionSequenceStep(ICS, T2);
2434 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002435 Sequence.AddDerivedToBaseCastStep(
2436 S.Context.getQualifiedType(T1,
2437 T2.getNonReferenceType().getQualifiers()),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002438 Category);
2439 else if (NewObjCConversion)
2440 Sequence.AddObjCObjectConversionStep(
2441 S.Context.getQualifiedType(T1,
2442 T2.getNonReferenceType().getQualifiers()));
2443
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002444 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002445 Sequence.AddQualificationConversionStep(cv1T1, Category);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002446
2447 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2448 return OR_Success;
2449}
2450
Sebastian Redld92badf2010-06-30 18:13:39 +00002451/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002452static void TryReferenceInitialization(Sema &S,
2453 const InitializedEntity &Entity,
2454 const InitializationKind &Kind,
2455 Expr *Initializer,
2456 InitializationSequence &Sequence) {
2457 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002458
Douglas Gregor1b303932009-12-22 15:35:07 +00002459 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002461 Qualifiers T1Quals;
2462 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002463 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002464 Qualifiers T2Quals;
2465 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002466 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002467
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002468 // If the initializer is the address of an overloaded function, try
2469 // to resolve the overloaded function. If all goes well, T2 is the
2470 // type of the resulting function.
2471 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002472 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002473 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2474 T1,
John McCall16df1e52010-03-30 21:47:33 +00002475 false,
2476 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 if (!Fn) {
2478 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2479 return;
2480 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002481
John McCall16df1e52010-03-30 21:47:33 +00002482 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 cv2T2 = Fn->getType();
2484 T2 = cv2T2.getUnqualifiedType();
2485 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 // Compute some basic properties of the types and the initializer.
2488 bool isLValueRef = DestType->isLValueReferenceType();
2489 bool isRValueRef = !isLValueRef;
2490 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002491 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002492 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002493 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002494 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2495 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002496
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002497 // C++0x [dcl.init.ref]p5:
2498 // A reference to type "cv1 T1" is initialized by an expression of type
2499 // "cv2 T2" as follows:
2500 //
2501 // - If the reference is an lvalue reference and the initializer
2502 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002503 // Note the analogous bullet points for rvlaue refs to functions. Because
2504 // there are no function rvalues in C++, rvalue refs to functions are treated
2505 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002506 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002507 bool T1Function = T1->isFunctionType();
2508 if (isLValueRef || T1Function) {
2509 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2511 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2512 // reference-compatible with "cv2 T2," or
2513 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002514 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002515 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002516 // can occur. However, we do pay attention to whether it is a bit-field
2517 // to decide whether we're actually binding to a temporary created from
2518 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002519 if (DerivedToBase)
2520 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002521 S.Context.getQualifiedType(T1, T2Quals),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002522 ImplicitCastExpr::LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002523 else if (ObjCConversion)
2524 Sequence.AddObjCObjectConversionStep(
2525 S.Context.getQualifiedType(T1, T2Quals));
2526
Chandler Carruth04bdce62010-01-12 20:32:25 +00002527 if (T1Quals != T2Quals)
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002528 Sequence.AddQualificationConversionStep(cv1T1,ImplicitCastExpr::LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002529 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002530 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002531 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 return;
2533 }
2534
2535 // - has a class type (i.e., T2 is a class type), where T1 is not
2536 // reference-related to T2, and can be implicitly converted to an
2537 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2538 // with "cv3 T3" (this conversion is selected by enumerating the
2539 // applicable conversion functions (13.3.1.6) and choosing the best
2540 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002541 // If we have an rvalue ref to function type here, the rhs must be
2542 // an rvalue.
2543 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2544 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002545 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2546 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002547 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002548 Sequence);
2549 if (ConvOvlResult == OR_Success)
2550 return;
John McCall0d1da222010-01-12 00:44:57 +00002551 if (ConvOvlResult != OR_No_Viable_Function) {
2552 Sequence.SetOverloadFailure(
2553 InitializationSequence::FK_ReferenceInitOverloadFailed,
2554 ConvOvlResult);
2555 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002556 }
2557 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002558
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559 // - Otherwise, the reference shall be an lvalue reference to a
2560 // non-volatile const type (i.e., cv1 shall be const), or the reference
2561 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002562 // be an rvalue or have a function type.
2563 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002564 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002565 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002566 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2567 Sequence.SetOverloadFailure(
2568 InitializationSequence::FK_ReferenceInitOverloadFailed,
2569 ConvOvlResult);
2570 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002571 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002572 ? (RefRelationship == Sema::Ref_Related
2573 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2574 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2575 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2576 else
2577 Sequence.SetFailed(
2578 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002579
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002580 return;
2581 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002582
2583 // - [If T1 is not a function type], if T2 is a class type and
2584 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002585 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002586 // - the initializer expression is an rvalue and "cv1 T1" is
2587 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002588 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002589 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002590 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2591 // compiler the freedom to perform a copy here or bind to the
2592 // object, while C++0x requires that we bind directly to the
2593 // object. Hence, we always bind to the object without making an
2594 // extra copy. However, in C++03 requires that we check for the
2595 // presence of a suitable copy constructor:
2596 //
2597 // The constructor that would be used to make the copy shall
2598 // be callable whether or not the copy is actually done.
2599 if (!S.getLangOptions().CPlusPlus0x)
2600 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2601
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002602 if (DerivedToBase)
2603 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002604 S.Context.getQualifiedType(T1, T2Quals),
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002605 isXValue ? ImplicitCastExpr::XValue
2606 : ImplicitCastExpr::RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002607 else if (ObjCConversion)
2608 Sequence.AddObjCObjectConversionStep(
2609 S.Context.getQualifiedType(T1, T2Quals));
2610
Chandler Carruth04bdce62010-01-12 20:32:25 +00002611 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002612 Sequence.AddQualificationConversionStep(cv1T1,
2613 isXValue ? ImplicitCastExpr::XValue
2614 : ImplicitCastExpr::RValue);
2615 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002616 return;
2617 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002618
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002619 // - T1 is not reference-related to T2 and the initializer expression
2620 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2621 // conversion is selected by enumerating the applicable conversion
2622 // functions (13.3.1.6) and choosing the best one through overload
2623 // resolution (13.3)),
2624 if (RefRelationship == Sema::Ref_Incompatible) {
2625 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2626 Kind, Initializer,
2627 /*AllowRValues=*/true,
2628 Sequence);
2629 if (ConvOvlResult)
2630 Sequence.SetOverloadFailure(
2631 InitializationSequence::FK_ReferenceInitOverloadFailed,
2632 ConvOvlResult);
2633
2634 return;
2635 }
2636
2637 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2638 return;
2639 }
2640
2641 // - If the initializer expression is an rvalue, with T2 an array type,
2642 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2643 // is bound to the object represented by the rvalue (see 3.10).
2644 // FIXME: How can an array type be reference-compatible with anything?
2645 // Don't we mean the element types of T1 and T2?
2646
2647 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2648 // from the initializer expression using the rules for a non-reference
2649 // copy initialization (8.5). The reference is then bound to the
2650 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002651
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002652 // Determine whether we are allowed to call explicit constructors or
2653 // explicit conversion operators.
2654 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002655
2656 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2657
2658 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2659 /*SuppressUserConversions*/ false,
2660 AllowExplicit,
2661 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002662 // FIXME: Use the conversion function set stored in ICS to turn
2663 // this into an overloading ambiguity diagnostic. However, we need
2664 // to keep that set as an OverloadCandidateSet rather than as some
2665 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002666 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2667 Sequence.SetOverloadFailure(
2668 InitializationSequence::FK_ReferenceInitOverloadFailed,
2669 ConvOvlResult);
2670 else
2671 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002672 return;
2673 }
2674
2675 // [...] If T1 is reference-related to T2, cv1 must be the
2676 // same cv-qualification as, or greater cv-qualification
2677 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002678 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2679 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002680 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002681 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2683 return;
2684 }
2685
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002686 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2687 return;
2688}
2689
2690/// \brief Attempt character array initialization from a string literal
2691/// (C++ [dcl.init.string], C99 6.7.8).
2692static void TryStringLiteralInitialization(Sema &S,
2693 const InitializedEntity &Entity,
2694 const InitializationKind &Kind,
2695 Expr *Initializer,
2696 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002697 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002698 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002699}
2700
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002701/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2702/// enumerates the constructors of the initialized entity and performs overload
2703/// resolution to select the best.
2704static void TryConstructorInitialization(Sema &S,
2705 const InitializedEntity &Entity,
2706 const InitializationKind &Kind,
2707 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002708 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002709 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002710 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002711
2712 // Build the candidate set directly in the initialization sequence
2713 // structure, so that it will persist if we fail.
2714 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2715 CandidateSet.clear();
2716
2717 // Determine whether we are allowed to call explicit constructors or
2718 // explicit conversion operators.
2719 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2720 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002721 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002722
2723 // The type we're constructing needs to be complete.
2724 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002725 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002726 return;
2727 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002728
2729 // The type we're converting to is a class type. Enumerate its constructors
2730 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002731 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2732 assert(DestRecordType && "Constructor initialization requires record type");
2733 CXXRecordDecl *DestRecordDecl
2734 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2735
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002736 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002737 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002738 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002739 NamedDecl *D = *Con;
2740 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002741 bool SuppressUserConversions = false;
2742
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002743 // Find the constructor (which may be a template).
2744 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002745 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002746 if (ConstructorTmpl)
2747 Constructor = cast<CXXConstructorDecl>(
2748 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002749 else {
John McCalla0296f72010-03-19 07:35:19 +00002750 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002751
2752 // If we're performing copy initialization using a copy constructor, we
2753 // suppress user-defined conversions on the arguments.
2754 // FIXME: Move constructors?
2755 if (Kind.getKind() == InitializationKind::IK_Copy &&
2756 Constructor->isCopyConstructor())
2757 SuppressUserConversions = true;
2758 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002759
2760 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002761 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002762 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002763 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002764 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002765 Args, NumArgs, CandidateSet,
2766 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002767 else
John McCalla0296f72010-03-19 07:35:19 +00002768 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002769 Args, NumArgs, CandidateSet,
2770 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002771 }
2772 }
2773
2774 SourceLocation DeclLoc = Kind.getLocation();
2775
2776 // Perform overload resolution. If it fails, return the failed result.
2777 OverloadCandidateSet::iterator Best;
2778 if (OverloadingResult Result
2779 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2780 Sequence.SetOverloadFailure(
2781 InitializationSequence::FK_ConstructorOverloadFailed,
2782 Result);
2783 return;
2784 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002785
2786 // C++0x [dcl.init]p6:
2787 // If a program calls for the default initialization of an object
2788 // of a const-qualified type T, T shall be a class type with a
2789 // user-provided default constructor.
2790 if (Kind.getKind() == InitializationKind::IK_Default &&
2791 Entity.getType().isConstQualified() &&
2792 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2793 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2794 return;
2795 }
2796
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002797 // Add the constructor initialization step. Any cv-qualification conversion is
2798 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002799 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002800 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002801 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002802 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002803}
2804
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002805/// \brief Attempt value initialization (C++ [dcl.init]p7).
2806static void TryValueInitialization(Sema &S,
2807 const InitializedEntity &Entity,
2808 const InitializationKind &Kind,
2809 InitializationSequence &Sequence) {
2810 // C++ [dcl.init]p5:
2811 //
2812 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002813 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002814
2815 // -- if T is an array type, then each element is value-initialized;
2816 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2817 T = AT->getElementType();
2818
2819 if (const RecordType *RT = T->getAs<RecordType>()) {
2820 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2821 // -- if T is a class type (clause 9) with a user-declared
2822 // constructor (12.1), then the default constructor for T is
2823 // called (and the initialization is ill-formed if T has no
2824 // accessible default constructor);
2825 //
2826 // FIXME: we really want to refer to a single subobject of the array,
2827 // but Entity doesn't have a way to capture that (yet).
2828 if (ClassDecl->hasUserDeclaredConstructor())
2829 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2830
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002831 // -- if T is a (possibly cv-qualified) non-union class type
2832 // without a user-provided constructor, then the object is
2833 // zero-initialized and, if T’s implicitly-declared default
2834 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002835 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002836 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002837 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002838 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2839 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002840 }
2841 }
2842
Douglas Gregor1b303932009-12-22 15:35:07 +00002843 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002844 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2845}
2846
Douglas Gregor85dabae2009-12-16 01:38:02 +00002847/// \brief Attempt default initialization (C++ [dcl.init]p6).
2848static void TryDefaultInitialization(Sema &S,
2849 const InitializedEntity &Entity,
2850 const InitializationKind &Kind,
2851 InitializationSequence &Sequence) {
2852 assert(Kind.getKind() == InitializationKind::IK_Default);
2853
2854 // C++ [dcl.init]p6:
2855 // To default-initialize an object of type T means:
2856 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002857 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002858 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2859 DestType = Array->getElementType();
2860
2861 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2862 // constructor for T is called (and the initialization is ill-formed if
2863 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002864 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002865 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2866 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002867 }
2868
2869 // - otherwise, no initialization is performed.
2870 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2871
2872 // If a program calls for the default initialization of an object of
2873 // a const-qualified type T, T shall be a class type with a user-provided
2874 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002875 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002876 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2877}
2878
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002879/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2880/// which enumerates all conversion functions and performs overload resolution
2881/// to select the best.
2882static void TryUserDefinedConversion(Sema &S,
2883 const InitializedEntity &Entity,
2884 const InitializationKind &Kind,
2885 Expr *Initializer,
2886 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002887 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2888
Douglas Gregor1b303932009-12-22 15:35:07 +00002889 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002890 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2891 QualType SourceType = Initializer->getType();
2892 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2893 "Must have a class type to perform a user-defined conversion");
2894
2895 // Build the candidate set directly in the initialization sequence
2896 // structure, so that it will persist if we fail.
2897 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2898 CandidateSet.clear();
2899
2900 // Determine whether we are allowed to call explicit constructors or
2901 // explicit conversion operators.
2902 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2903
2904 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2905 // The type we're converting to is a class type. Enumerate its constructors
2906 // to see if there is a suitable conversion.
2907 CXXRecordDecl *DestRecordDecl
2908 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2909
Douglas Gregord9848152010-04-26 14:36:57 +00002910 // Try to complete the type we're converting to.
2911 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002912 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002913 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002914 Con != ConEnd; ++Con) {
2915 NamedDecl *D = *Con;
2916 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002917
Douglas Gregord9848152010-04-26 14:36:57 +00002918 // Find the constructor (which may be a template).
2919 CXXConstructorDecl *Constructor = 0;
2920 FunctionTemplateDecl *ConstructorTmpl
2921 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002922 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002923 Constructor = cast<CXXConstructorDecl>(
2924 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002925 else
Douglas Gregord9848152010-04-26 14:36:57 +00002926 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002927
2928 if (!Constructor->isInvalidDecl() &&
2929 Constructor->isConvertingConstructor(AllowExplicit)) {
2930 if (ConstructorTmpl)
2931 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2932 /*ExplicitArgs*/ 0,
2933 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002934 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002935 else
2936 S.AddOverloadCandidate(Constructor, FoundDecl,
2937 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002938 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002939 }
2940 }
2941 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002942 }
Eli Friedman78275202009-12-19 08:11:05 +00002943
2944 SourceLocation DeclLoc = Initializer->getLocStart();
2945
Douglas Gregor540c3b02009-12-14 17:27:33 +00002946 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2947 // The type we're converting from is a class type, enumerate its conversion
2948 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002949
Eli Friedman4afe9a32009-12-20 22:12:03 +00002950 // We can only enumerate the conversion functions for a complete type; if
2951 // the type isn't complete, simply skip this step.
2952 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2953 CXXRecordDecl *SourceRecordDecl
2954 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002955
John McCallad371252010-01-20 00:46:10 +00002956 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002957 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002958 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002959 E = Conversions->end();
2960 I != E; ++I) {
2961 NamedDecl *D = *I;
2962 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2963 if (isa<UsingShadowDecl>(D))
2964 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2965
2966 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2967 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002968 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002969 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002970 else
John McCallda4458e2010-03-31 01:36:47 +00002971 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002972
2973 if (AllowExplicit || !Conv->isExplicit()) {
2974 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002975 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002976 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002977 CandidateSet);
2978 else
John McCalla0296f72010-03-19 07:35:19 +00002979 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002980 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002981 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002982 }
2983 }
2984 }
2985
Douglas Gregor540c3b02009-12-14 17:27:33 +00002986 // Perform overload resolution. If it fails, return the failed result.
2987 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002988 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002989 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2990 Sequence.SetOverloadFailure(
2991 InitializationSequence::FK_UserConversionOverloadFailed,
2992 Result);
2993 return;
2994 }
John McCall0d1da222010-01-12 00:44:57 +00002995
Douglas Gregor540c3b02009-12-14 17:27:33 +00002996 FunctionDecl *Function = Best->Function;
2997
2998 if (isa<CXXConstructorDecl>(Function)) {
2999 // Add the user-defined conversion step. Any cv-qualification conversion is
3000 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003001 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003002 return;
3003 }
3004
3005 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003006 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003007 if (ConvType->getAs<RecordType>()) {
3008 // If we're converting to a class type, there may be an copy if
3009 // the resulting temporary object (possible to create an object of
3010 // a base class type). That copy is not a separate conversion, so
3011 // we just make a note of the actual destination type (possibly a
3012 // base class of the type returned by the conversion function) and
3013 // let the user-defined conversion step handle the conversion.
3014 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3015 return;
3016 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003017
Douglas Gregor5ab11652010-04-17 22:01:05 +00003018 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3019
3020 // If the conversion following the call to the conversion function
3021 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003022 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3023 Best->FinalConversion.Third) {
3024 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003025 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003026 ICS.Standard = Best->FinalConversion;
3027 Sequence.AddConversionSequenceStep(ICS, DestType);
3028 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003029}
3030
John McCallec6f4e92010-06-04 02:29:22 +00003031bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
3032 const InitializedEntity &Entity,
3033 Expr *Initializer,
3034 bool SuppressUserConversions,
3035 bool AllowExplicitConversions,
3036 bool InOverloadResolution) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003037 ImplicitConversionSequence ICS
John McCallec6f4e92010-06-04 02:29:22 +00003038 = TryImplicitConversion(Initializer, Entity.getType(),
3039 SuppressUserConversions,
3040 AllowExplicitConversions,
3041 InOverloadResolution);
3042 if (ICS.isBad()) return true;
3043
3044 // Perform the actual conversion.
Douglas Gregor1b303932009-12-22 15:35:07 +00003045 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
John McCallec6f4e92010-06-04 02:29:22 +00003046 return false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003047}
3048
3049InitializationSequence::InitializationSequence(Sema &S,
3050 const InitializedEntity &Entity,
3051 const InitializationKind &Kind,
3052 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003053 unsigned NumArgs)
3054 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003055 ASTContext &Context = S.Context;
3056
3057 // C++0x [dcl.init]p16:
3058 // The semantics of initializers are as follows. The destination type is
3059 // the type of the object or reference being initialized and the source
3060 // type is the type of the initializer expression. The source type is not
3061 // defined when the initializer is a braced-init-list or when it is a
3062 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003063 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003064
3065 if (DestType->isDependentType() ||
3066 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3067 SequenceKind = DependentSequence;
3068 return;
3069 }
3070
3071 QualType SourceType;
3072 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003073 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003074 Initializer = Args[0];
3075 if (!isa<InitListExpr>(Initializer))
3076 SourceType = Initializer->getType();
3077 }
3078
3079 // - If the initializer is a braced-init-list, the object is
3080 // list-initialized (8.5.4).
3081 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3082 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003083 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003084 }
3085
3086 // - If the destination type is a reference type, see 8.5.3.
3087 if (DestType->isReferenceType()) {
3088 // C++0x [dcl.init.ref]p1:
3089 // A variable declared to be a T& or T&&, that is, "reference to type T"
3090 // (8.3.2), shall be initialized by an object, or function, of type T or
3091 // by an object that can be converted into a T.
3092 // (Therefore, multiple arguments are not permitted.)
3093 if (NumArgs != 1)
3094 SetFailed(FK_TooManyInitsForReference);
3095 else
3096 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3097 return;
3098 }
3099
3100 // - If the destination type is an array of characters, an array of
3101 // char16_t, an array of char32_t, or an array of wchar_t, and the
3102 // initializer is a string literal, see 8.5.2.
3103 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3104 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3105 return;
3106 }
3107
3108 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003109 if (Kind.getKind() == InitializationKind::IK_Value ||
3110 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003111 TryValueInitialization(S, Entity, Kind, *this);
3112 return;
3113 }
3114
Douglas Gregor85dabae2009-12-16 01:38:02 +00003115 // Handle default initialization.
3116 if (Kind.getKind() == InitializationKind::IK_Default){
3117 TryDefaultInitialization(S, Entity, Kind, *this);
3118 return;
3119 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003120
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003121 // - Otherwise, if the destination type is an array, the program is
3122 // ill-formed.
3123 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3124 if (AT->getElementType()->isAnyCharacterType())
3125 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3126 else
3127 SetFailed(FK_ArrayNeedsInitList);
3128
3129 return;
3130 }
Eli Friedman78275202009-12-19 08:11:05 +00003131
3132 // Handle initialization in C
3133 if (!S.getLangOptions().CPlusPlus) {
3134 setSequenceKind(CAssignment);
3135 AddCAssignmentStep(DestType);
3136 return;
3137 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138
3139 // - If the destination type is a (possibly cv-qualified) class type:
3140 if (DestType->isRecordType()) {
3141 // - If the initialization is direct-initialization, or if it is
3142 // copy-initialization where the cv-unqualified version of the
3143 // source type is the same class as, or a derived class of, the
3144 // class of the destination, constructors are considered. [...]
3145 if (Kind.getKind() == InitializationKind::IK_Direct ||
3146 (Kind.getKind() == InitializationKind::IK_Copy &&
3147 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3148 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003149 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003150 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003151 // - Otherwise (i.e., for the remaining copy-initialization cases),
3152 // user-defined conversion sequences that can convert from the source
3153 // type to the destination type or (when a conversion function is
3154 // used) to a derived class thereof are enumerated as described in
3155 // 13.3.1.4, and the best one is chosen through overload resolution
3156 // (13.3).
3157 else
3158 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3159 return;
3160 }
3161
Douglas Gregor85dabae2009-12-16 01:38:02 +00003162 if (NumArgs > 1) {
3163 SetFailed(FK_TooManyInitsForScalar);
3164 return;
3165 }
3166 assert(NumArgs == 1 && "Zero-argument case handled above");
3167
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003168 // - Otherwise, if the source type is a (possibly cv-qualified) class
3169 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003170 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3172 return;
3173 }
3174
3175 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003176 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 // conversions (Clause 4) will be used, if necessary, to convert the
3178 // initializer expression to the cv-unqualified version of the
3179 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003180 if (S.TryImplicitConversion(*this, Entity, Initializer,
3181 /*SuppressUserConversions*/ true,
3182 /*AllowExplicitConversions*/ false,
3183 /*InOverloadResolution*/ false))
3184 SetFailed(InitializationSequence::FK_ConversionFailed);
3185 else
3186 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003187}
3188
3189InitializationSequence::~InitializationSequence() {
3190 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3191 StepEnd = Steps.end();
3192 Step != StepEnd; ++Step)
3193 Step->Destroy();
3194}
3195
3196//===----------------------------------------------------------------------===//
3197// Perform initialization
3198//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003199static Sema::AssignmentAction
3200getAssignmentAction(const InitializedEntity &Entity) {
3201 switch(Entity.getKind()) {
3202 case InitializedEntity::EK_Variable:
3203 case InitializedEntity::EK_New:
3204 return Sema::AA_Initializing;
3205
3206 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003207 if (Entity.getDecl() &&
3208 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3209 return Sema::AA_Sending;
3210
Douglas Gregore1314a62009-12-18 05:02:21 +00003211 return Sema::AA_Passing;
3212
3213 case InitializedEntity::EK_Result:
3214 return Sema::AA_Returning;
3215
3216 case InitializedEntity::EK_Exception:
3217 case InitializedEntity::EK_Base:
3218 llvm_unreachable("No assignment action for C++-specific initialization");
3219 break;
3220
3221 case InitializedEntity::EK_Temporary:
3222 // FIXME: Can we tell apart casting vs. converting?
3223 return Sema::AA_Casting;
3224
3225 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003226 case InitializedEntity::EK_ArrayElement:
3227 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003228 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003229 return Sema::AA_Initializing;
3230 }
3231
3232 return Sema::AA_Converting;
3233}
3234
Douglas Gregor95562572010-04-24 23:45:46 +00003235/// \brief Whether we should binding a created object as a temporary when
3236/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003237static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003238 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003239 case InitializedEntity::EK_ArrayElement:
3240 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003241 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003242 case InitializedEntity::EK_New:
3243 case InitializedEntity::EK_Variable:
3244 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003245 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003246 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003247 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003248 return false;
3249
3250 case InitializedEntity::EK_Parameter:
3251 case InitializedEntity::EK_Temporary:
3252 return true;
3253 }
3254
3255 llvm_unreachable("missed an InitializedEntity kind?");
3256}
3257
Douglas Gregor95562572010-04-24 23:45:46 +00003258/// \brief Whether the given entity, when initialized with an object
3259/// created for that initialization, requires destruction.
3260static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3261 switch (Entity.getKind()) {
3262 case InitializedEntity::EK_Member:
3263 case InitializedEntity::EK_Result:
3264 case InitializedEntity::EK_New:
3265 case InitializedEntity::EK_Base:
3266 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003267 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003268 return false;
3269
3270 case InitializedEntity::EK_Variable:
3271 case InitializedEntity::EK_Parameter:
3272 case InitializedEntity::EK_Temporary:
3273 case InitializedEntity::EK_ArrayElement:
3274 case InitializedEntity::EK_Exception:
3275 return true;
3276 }
3277
3278 llvm_unreachable("missed an InitializedEntity kind?");
3279}
3280
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003281/// \brief Make a (potentially elidable) temporary copy of the object
3282/// provided by the given initializer by calling the appropriate copy
3283/// constructor.
3284///
3285/// \param S The Sema object used for type-checking.
3286///
3287/// \param T The type of the temporary object, which must either by
3288/// the type of the initializer expression or a superclass thereof.
3289///
3290/// \param Enter The entity being initialized.
3291///
3292/// \param CurInit The initializer expression.
3293///
3294/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3295/// is permitted in C++03 (but not C++0x) when binding a reference to
3296/// an rvalue.
3297///
3298/// \returns An expression that copies the initializer expression into
3299/// a temporary object, or an error expression if a copy could not be
3300/// created.
John McCalldadc5752010-08-24 06:29:42 +00003301static ExprResult CopyObject(Sema &S,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003302 QualType T,
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003303 const InitializedEntity &Entity,
John McCalldadc5752010-08-24 06:29:42 +00003304 ExprResult CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003305 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003306 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003307 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003308 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003309 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003310 Class = cast<CXXRecordDecl>(Record->getDecl());
3311 if (!Class)
3312 return move(CurInit);
3313
3314 // C++0x [class.copy]p34:
3315 // When certain criteria are met, an implementation is allowed to
3316 // omit the copy/move construction of a class object, even if the
3317 // copy/move constructor and/or destructor for the object have
3318 // side effects. [...]
3319 // - when a temporary class object that has not been bound to a
3320 // reference (12.2) would be copied/moved to a class object
3321 // with the same cv-unqualified type, the copy/move operation
3322 // can be omitted by constructing the temporary object
3323 // directly into the target of the omitted copy/move
3324 //
3325 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003326 // elision for return statements and throw expressions are handled as part
3327 // of constructor initialization, while copy elision for exception handlers
3328 // is handled by the run-time.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003329 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003330 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregore1314a62009-12-18 05:02:21 +00003331 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003332 switch (Entity.getKind()) {
3333 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003334 Loc = Entity.getReturnLoc();
3335 break;
3336
3337 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003338 Loc = Entity.getThrowLoc();
3339 break;
3340
3341 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003342 Loc = Entity.getDecl()->getLocation();
3343 break;
3344
Anders Carlsson0bd52402010-01-24 00:19:41 +00003345 case InitializedEntity::EK_ArrayElement:
3346 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003347 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003348 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003349 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003350 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003351 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003352 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003353 Loc = CurInitExpr->getLocStart();
3354 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003355 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003356
3357 // Make sure that the type we are copying is complete.
3358 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3359 return move(CurInit);
3360
Douglas Gregore1314a62009-12-18 05:02:21 +00003361 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003362 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003363 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003364 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003365 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003366 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003367 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3368 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003369 !Constructor->isCopyConstructor() ||
3370 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003371 continue;
John McCalla0296f72010-03-19 07:35:19 +00003372
3373 DeclAccessPair FoundDecl
3374 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3375 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003376 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003377 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003378
3379 OverloadCandidateSet::iterator Best;
3380 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3381 case OR_Success:
3382 break;
3383
3384 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003385 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3386 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3387 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003388 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003389 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003390 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3391 &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003392 if (!IsExtraneousCopy || S.isSFINAEContext())
3393 return S.ExprError();
3394 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003395
3396 case OR_Ambiguous:
3397 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003398 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003399 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003400 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3401 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003402 return S.ExprError();
3403
3404 case OR_Deleted:
3405 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003406 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003407 << CurInitExpr->getSourceRange();
3408 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3409 << Best->Function->isDeleted();
3410 return S.ExprError();
3411 }
3412
Douglas Gregor5ab11652010-04-17 22:01:05 +00003413 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003414 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003415 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003416
Anders Carlssona01874b2010-04-21 18:47:17 +00003417 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003418 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003419
3420 if (IsExtraneousCopy) {
3421 // If this is a totally extraneous copy for C++03 reference
3422 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003423 // expression. We don't generate an (elided) copy operation here
3424 // because doing so would require us to pass down a flag to avoid
3425 // infinite recursion, where each step adds another extraneous,
3426 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003427
Douglas Gregor30b52772010-04-18 07:57:34 +00003428 // Instantiate the default arguments of any extra parameters in
3429 // the selected copy constructor, as if we were going to create a
3430 // proper call to the copy constructor.
3431 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3432 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3433 if (S.RequireCompleteType(Loc, Parm->getType(),
3434 S.PDiag(diag::err_call_incomplete_argument)))
3435 break;
3436
3437 // Build the default argument expression; we don't actually care
3438 // if this succeeds or not, because this routine will complain
3439 // if there was a problem.
3440 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3441 }
3442
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003443 return S.Owned(CurInitExpr);
3444 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003445
3446 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003447 // constructor call (we might have derived-to-base conversions, or
3448 // the copy constructor may have default arguments).
Douglas Gregor5ab11652010-04-17 22:01:05 +00003449 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003450 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003451 Loc, ConstructorArgs))
3452 return S.ExprError();
3453
Douglas Gregord0ace022010-04-25 00:55:24 +00003454 // Actually perform the constructor call.
3455 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
3456 move_arg(ConstructorArgs));
3457
3458 // If we're supposed to bind temporaries, do so.
3459 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3460 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3461 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003462}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003463
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003464void InitializationSequence::PrintInitLocationNote(Sema &S,
3465 const InitializedEntity &Entity) {
3466 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3467 if (Entity.getDecl()->getLocation().isInvalid())
3468 return;
3469
3470 if (Entity.getDecl()->getDeclName())
3471 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3472 << Entity.getDecl()->getDeclName();
3473 else
3474 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3475 }
3476}
3477
John McCalldadc5752010-08-24 06:29:42 +00003478ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003479InitializationSequence::Perform(Sema &S,
3480 const InitializedEntity &Entity,
3481 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003482 Action::MultiExprArg Args,
3483 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003484 if (SequenceKind == FailedSequence) {
3485 unsigned NumArgs = Args.size();
3486 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3487 return S.ExprError();
3488 }
3489
3490 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003491 // If the declaration is a non-dependent, incomplete array type
3492 // that has an initializer, then its type will be completed once
3493 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003494 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003495 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003496 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003497 if (const IncompleteArrayType *ArrayT
3498 = S.Context.getAsIncompleteArrayType(DeclType)) {
3499 // FIXME: We don't currently have the ability to accurately
3500 // compute the length of an initializer list without
3501 // performing full type-checking of the initializer list
3502 // (since we have to determine where braces are implicitly
3503 // introduced and such). So, we fall back to making the array
3504 // type a dependently-sized array type with no specified
3505 // bound.
3506 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3507 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003508
Douglas Gregor51e77d52009-12-10 17:56:55 +00003509 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003510 if (DeclaratorDecl *DD = Entity.getDecl()) {
3511 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3512 TypeLoc TL = TInfo->getTypeLoc();
3513 if (IncompleteArrayTypeLoc *ArrayLoc
3514 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3515 Brackets = ArrayLoc->getBracketsRange();
3516 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003517 }
3518
3519 *ResultType
3520 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3521 /*NumElts=*/0,
3522 ArrayT->getSizeModifier(),
3523 ArrayT->getIndexTypeCVRQualifiers(),
3524 Brackets);
3525 }
3526
3527 }
3528 }
3529
Eli Friedmana553d4a2009-12-22 02:35:53 +00003530 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003531 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003533 if (Args.size() == 0)
3534 return S.Owned((Expr *)0);
3535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003536 unsigned NumArgs = Args.size();
3537 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3538 SourceLocation(),
3539 (Expr **)Args.release(),
3540 NumArgs,
3541 SourceLocation()));
3542 }
3543
Douglas Gregor85dabae2009-12-16 01:38:02 +00003544 if (SequenceKind == NoInitialization)
3545 return S.Owned((Expr *)0);
3546
Douglas Gregor1b303932009-12-22 15:35:07 +00003547 QualType DestType = Entity.getType().getNonReferenceType();
3548 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003549 // the same as Entity.getDecl()->getType() in cases involving type merging,
3550 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003551 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003552 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003553 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003554
John McCalldadc5752010-08-24 06:29:42 +00003555 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003556
3557 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3558
3559 // For initialization steps that start with a single initializer,
3560 // grab the only argument out the Args and place it into the "current"
3561 // initializer.
3562 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003563 case SK_ResolveAddressOfOverloadedFunction:
3564 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003565 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003566 case SK_CastDerivedToBaseLValue:
3567 case SK_BindReference:
3568 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003569 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003570 case SK_UserConversion:
3571 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003572 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003573 case SK_QualificationConversionRValue:
3574 case SK_ConversionSequence:
3575 case SK_ListInitialization:
3576 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003577 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003578 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003579 assert(Args.size() == 1);
John McCalldadc5752010-08-24 06:29:42 +00003580 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregore1314a62009-12-18 05:02:21 +00003581 if (CurInit.isInvalid())
3582 return S.ExprError();
3583 break;
3584
3585 case SK_ConstructorInitialization:
3586 case SK_ZeroInitialization:
3587 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003588 }
3589
3590 // Walk through the computed steps for the initialization sequence,
3591 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003592 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003593 for (step_iterator Step = step_begin(), StepEnd = step_end();
3594 Step != StepEnd; ++Step) {
3595 if (CurInit.isInvalid())
3596 return S.ExprError();
3597
3598 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003599 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003600
3601 switch (Step->Kind) {
3602 case SK_ResolveAddressOfOverloadedFunction:
3603 // Overload resolution determined which function invoke; update the
3604 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003605 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003606 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003607 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003608 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003609 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 break;
3611
3612 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003613 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 case SK_CastDerivedToBaseLValue: {
3615 // We have a derived-to-base cast that produces either an rvalue or an
3616 // lvalue. Perform that cast.
3617
John McCallcf142162010-08-07 06:22:56 +00003618 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003619
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620 // Casts to inaccessible base classes are allowed with C-style casts.
3621 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3622 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3623 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003624 CurInitExpr->getSourceRange(),
3625 &BasePath, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003626 return S.ExprError();
3627
Douglas Gregor88d292c2010-05-13 16:44:06 +00003628 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3629 QualType T = SourceType;
3630 if (const PointerType *Pointer = T->getAs<PointerType>())
3631 T = Pointer->getPointeeType();
3632 if (const RecordType *RecordTy = T->getAs<RecordType>())
3633 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3634 cast<CXXRecordDecl>(RecordTy->getDecl()));
3635 }
3636
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003637 ImplicitCastExpr::ResultCategory Category =
3638 Step->Kind == SK_CastDerivedToBaseLValue ?
3639 ImplicitCastExpr::LValue :
3640 (Step->Kind == SK_CastDerivedToBaseXValue ?
3641 ImplicitCastExpr::XValue :
3642 ImplicitCastExpr::RValue);
John McCallcf142162010-08-07 06:22:56 +00003643 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3644 Step->Type,
3645 CastExpr::CK_DerivedToBase,
3646 (Expr*)CurInit.release(),
3647 &BasePath, Category));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 break;
3649 }
3650
3651 case SK_BindReference:
3652 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3653 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3654 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003655 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 << BitField->getDeclName()
3657 << CurInitExpr->getSourceRange();
3658 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3659 return S.ExprError();
3660 }
Anders Carlssona91be642010-01-29 02:47:33 +00003661
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003662 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003663 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003664 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3665 << Entity.getType().isVolatileQualified()
3666 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003667 PrintInitLocationNote(S, Entity);
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003668 return S.ExprError();
3669 }
3670
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003671 // Reference binding does not have any corresponding ASTs.
3672
3673 // Check exception specifications
3674 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3675 return S.ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003676
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003677 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003678
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003679 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003680 // Reference binding does not have any corresponding ASTs.
3681
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003682 // Check exception specifications
3683 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3684 return S.ExprError();
3685
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 break;
3687
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003688 case SK_ExtraneousCopyToTemporary:
3689 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3690 /*IsExtraneousCopy=*/true);
3691 break;
3692
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693 case SK_UserConversion: {
3694 // We have a user-defined conversion that invokes either a constructor
3695 // or a conversion function.
3696 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003697 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003698 FunctionDecl *Fn = Step->Function.Function;
3699 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003700 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003701 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003702 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003703 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003704 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003705 SourceLocation Loc = CurInitExpr->getLocStart();
3706 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003707
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003708 // Determine the arguments required to actually perform the constructor
3709 // call.
3710 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003711 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003712 Loc, ConstructorArgs))
3713 return S.ExprError();
3714
3715 // Build the an expression that constructs a temporary.
3716 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3717 move_arg(ConstructorArgs));
3718 if (CurInit.isInvalid())
3719 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003720
Anders Carlssona01874b2010-04-21 18:47:17 +00003721 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003722 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003723 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724
3725 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003726 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3727 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3728 S.IsDerivedFrom(SourceType, Class))
3729 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003730
3731 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003732 } else {
3733 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003734 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003735 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003736 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003737 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003738 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003739
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003740 // FIXME: Should we move this initialization into a separate
3741 // derived-to-base conversion? I believe the answer is "no", because
3742 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003743 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003744 FoundFn, Conversion))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003745 return S.ExprError();
3746
3747 // Do a little dance to make sure that CurInit has the proper
3748 // pointer.
3749 CurInit.release();
3750
3751 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003752 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3753 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003754 if (CurInit.isInvalid() || !CurInit.get())
3755 return S.ExprError();
3756
3757 CastKind = CastExpr::CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003758
3759 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003760 }
3761
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003762 bool RequiresCopy = !IsCopy &&
3763 getKind() != InitializationSequence::ReferenceBinding;
3764 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003765 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003766 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3767 CurInitExpr = static_cast<Expr *>(CurInit.get());
3768 QualType T = CurInitExpr->getType();
3769 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003770 CXXDestructorDecl *Destructor
3771 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003772 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3773 S.PDiag(diag::err_access_dtor_temp) << T);
3774 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3775 }
3776 }
3777
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003779 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003780 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3781 CurInitExpr->getType(),
3782 CastKind, CurInitExpr, 0,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003783 IsLvalue ? ImplicitCastExpr::LValue : ImplicitCastExpr::RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003784
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003785 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003786 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3787 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003788
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003789 break;
3790 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003792 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003793 case SK_QualificationConversionXValue:
3794 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003795 // Perform a qualification conversion; these can never go wrong.
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003796 ImplicitCastExpr::ResultCategory Category =
3797 Step->Kind == SK_QualificationConversionLValue ?
3798 ImplicitCastExpr::LValue :
3799 (Step->Kind == SK_QualificationConversionXValue ?
3800 ImplicitCastExpr::XValue :
3801 ImplicitCastExpr::RValue);
3802 S.ImpCastExprToType(CurInitExpr, Step->Type, CastExpr::CK_NoOp, Category);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003803 CurInit.release();
3804 CurInit = S.Owned(CurInitExpr);
3805 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003806 }
3807
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003808 case SK_ConversionSequence: {
3809 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3810
3811 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3812 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003813 return S.ExprError();
3814
3815 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003816 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003817 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003818 }
3819
Douglas Gregor51e77d52009-12-10 17:56:55 +00003820 case SK_ListInitialization: {
3821 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3822 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003823 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003824 return S.ExprError();
3825
3826 CurInit.release();
3827 CurInit = S.Owned(InitList);
3828 break;
3829 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003830
3831 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003832 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003833 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003834 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003835
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003836 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003837 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003838 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3839 ? Kind.getEqualLoc()
3840 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003841
3842 if (Kind.getKind() == InitializationKind::IK_Default) {
3843 // Force even a trivial, implicit default constructor to be
3844 // semantically checked. We do this explicitly because we don't build
3845 // the definition for completely trivial constructors.
3846 CXXRecordDecl *ClassDecl = Constructor->getParent();
3847 assert(ClassDecl && "No parent class for constructor.");
3848 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3849 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3850 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3851 }
3852
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003853 // Determine the arguments required to actually perform the constructor
3854 // call.
3855 if (S.CompleteConstructorCall(Constructor, move(Args),
3856 Loc, ConstructorArgs))
3857 return S.ExprError();
3858
Chandler Carruthc9262402010-08-23 07:55:51 +00003859
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003860 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003861 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003862 (Kind.getKind() == InitializationKind::IK_Direct ||
3863 Kind.getKind() == InitializationKind::IK_Value)) {
3864 // An explicitly-constructed temporary, e.g., X(1, 2).
3865 unsigned NumExprs = ConstructorArgs.size();
3866 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003867 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003868 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3869 Constructor,
3870 Entity.getType(),
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003871 Loc,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003872 Exprs,
3873 NumExprs,
Douglas Gregor199db362010-04-27 20:36:09 +00003874 Kind.getParenRange().getEnd(),
3875 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003876 } else {
3877 CXXConstructExpr::ConstructionKind ConstructKind =
3878 CXXConstructExpr::CK_Complete;
3879
3880 if (Entity.getKind() == InitializedEntity::EK_Base) {
3881 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3882 CXXConstructExpr::CK_VirtualBase :
3883 CXXConstructExpr::CK_NonVirtualBase;
3884 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003885
3886 // If the entity allows NRVO, mark the construction as elidable
3887 // unconditionally.
3888 if (Entity.allowsNRVO())
3889 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3890 Constructor, /*Elidable=*/true,
3891 move_arg(ConstructorArgs),
3892 ConstructorInitRequiresZeroInit,
3893 ConstructKind);
3894 else
3895 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3896 Constructor,
3897 move_arg(ConstructorArgs),
3898 ConstructorInitRequiresZeroInit,
3899 ConstructKind);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003900 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003901 if (CurInit.isInvalid())
3902 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003903
3904 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003905 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003906 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003907 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003908
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003909 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003910 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003911
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003912 break;
3913 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003914
3915 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003916 step_iterator NextStep = Step;
3917 ++NextStep;
3918 if (NextStep != StepEnd &&
3919 NextStep->Kind == SK_ConstructorInitialization) {
3920 // The need for zero-initialization is recorded directly into
3921 // the call to the object's constructor within the next step.
3922 ConstructorInitRequiresZeroInit = true;
3923 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3924 S.getLangOptions().CPlusPlus &&
3925 !Kind.isImplicitValueInit()) {
Douglas Gregor747eb782010-07-08 06:14:04 +00003926 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003927 Kind.getRange().getBegin(),
3928 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003929 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003930 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003931 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003932 break;
3933 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003934
3935 case SK_CAssignment: {
3936 QualType SourceType = CurInitExpr->getType();
3937 Sema::AssignConvertType ConvTy =
3938 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003939
3940 // If this is a call, allow conversion to a transparent union.
3941 if (ConvTy != Sema::Compatible &&
3942 Entity.getKind() == InitializedEntity::EK_Parameter &&
3943 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3944 == Sema::Compatible)
3945 ConvTy = Sema::Compatible;
3946
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003947 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003948 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3949 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003950 CurInitExpr,
3951 getAssignmentAction(Entity),
3952 &Complained)) {
3953 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003954 return S.ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003955 } else if (Complained)
3956 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003957
3958 CurInit.release();
3959 CurInit = S.Owned(CurInitExpr);
3960 break;
3961 }
Eli Friedman78275202009-12-19 08:11:05 +00003962
3963 case SK_StringInit: {
3964 QualType Ty = Step->Type;
3965 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3966 break;
3967 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003968
3969 case SK_ObjCObjectConversion:
3970 S.ImpCastExprToType(CurInitExpr, Step->Type,
3971 CastExpr::CK_ObjCObjectLValueCast,
3972 S.CastCategory(CurInitExpr));
3973 CurInit.release();
3974 CurInit = S.Owned(CurInitExpr);
3975 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003976 }
3977 }
3978
3979 return move(CurInit);
3980}
3981
3982//===----------------------------------------------------------------------===//
3983// Diagnose initialization failures
3984//===----------------------------------------------------------------------===//
3985bool InitializationSequence::Diagnose(Sema &S,
3986 const InitializedEntity &Entity,
3987 const InitializationKind &Kind,
3988 Expr **Args, unsigned NumArgs) {
3989 if (SequenceKind != FailedSequence)
3990 return false;
3991
Douglas Gregor1b303932009-12-22 15:35:07 +00003992 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003993 switch (Failure) {
3994 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003995 // FIXME: Customize for the initialized entity?
3996 if (NumArgs == 0)
3997 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3998 << DestType.getNonReferenceType();
3999 else // FIXME: diagnostic below could be better!
4000 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4001 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004002 break;
4003
4004 case FK_ArrayNeedsInitList:
4005 case FK_ArrayNeedsInitListOrStringLiteral:
4006 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4007 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4008 break;
4009
John McCall16df1e52010-03-30 21:47:33 +00004010 case FK_AddressOfOverloadFailed: {
4011 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012 S.ResolveAddressOfOverloadedFunction(Args[0],
4013 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004014 true,
4015 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004016 break;
John McCall16df1e52010-03-30 21:47:33 +00004017 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004018
4019 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004020 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004021 switch (FailedOverloadResult) {
4022 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004023 if (Failure == FK_UserConversionOverloadFailed)
4024 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4025 << Args[0]->getType() << DestType
4026 << Args[0]->getSourceRange();
4027 else
4028 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4029 << DestType << Args[0]->getType()
4030 << Args[0]->getSourceRange();
4031
John McCallad907772010-01-12 07:18:19 +00004032 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
4033 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 break;
4035
4036 case OR_No_Viable_Function:
4037 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4038 << Args[0]->getType() << DestType.getNonReferenceType()
4039 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00004040 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4041 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004042 break;
4043
4044 case OR_Deleted: {
4045 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4046 << Args[0]->getType() << DestType.getNonReferenceType()
4047 << Args[0]->getSourceRange();
4048 OverloadCandidateSet::iterator Best;
4049 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4050 Kind.getLocation(),
4051 Best);
4052 if (Ovl == OR_Deleted) {
4053 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4054 << Best->Function->isDeleted();
4055 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004056 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 }
4058 break;
4059 }
4060
4061 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004062 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004063 break;
4064 }
4065 break;
4066
4067 case FK_NonConstLValueReferenceBindingToTemporary:
4068 case FK_NonConstLValueReferenceBindingToUnrelated:
4069 S.Diag(Kind.getLocation(),
4070 Failure == FK_NonConstLValueReferenceBindingToTemporary
4071 ? diag::err_lvalue_reference_bind_to_temporary
4072 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004073 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 << DestType.getNonReferenceType()
4075 << Args[0]->getType()
4076 << Args[0]->getSourceRange();
4077 break;
4078
4079 case FK_RValueReferenceBindingToLValue:
4080 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4081 << Args[0]->getSourceRange();
4082 break;
4083
4084 case FK_ReferenceInitDropsQualifiers:
4085 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4086 << DestType.getNonReferenceType()
4087 << Args[0]->getType()
4088 << Args[0]->getSourceRange();
4089 break;
4090
4091 case FK_ReferenceInitFailed:
4092 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4093 << DestType.getNonReferenceType()
4094 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4095 << Args[0]->getType()
4096 << Args[0]->getSourceRange();
4097 break;
4098
4099 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004100 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4101 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004102 << DestType
4103 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4104 << Args[0]->getType()
4105 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004106 break;
4107
4108 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004109 SourceRange R;
4110
4111 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4112 R = SourceRange(InitList->getInit(1)->getLocStart(),
4113 InitList->getLocEnd());
4114 else
4115 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004116
4117 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00004118 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004119 break;
4120 }
4121
4122 case FK_ReferenceBindingToInitList:
4123 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4124 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4125 break;
4126
4127 case FK_InitListBadDestinationType:
4128 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4129 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4130 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004131
4132 case FK_ConstructorOverloadFailed: {
4133 SourceRange ArgsRange;
4134 if (NumArgs)
4135 ArgsRange = SourceRange(Args[0]->getLocStart(),
4136 Args[NumArgs - 1]->getLocEnd());
4137
4138 // FIXME: Using "DestType" for the entity we're printing is probably
4139 // bad.
4140 switch (FailedOverloadResult) {
4141 case OR_Ambiguous:
4142 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4143 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00004144 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00004145 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004146 break;
4147
4148 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004149 if (Kind.getKind() == InitializationKind::IK_Default &&
4150 (Entity.getKind() == InitializedEntity::EK_Base ||
4151 Entity.getKind() == InitializedEntity::EK_Member) &&
4152 isa<CXXConstructorDecl>(S.CurContext)) {
4153 // This is implicit default initialization of a member or
4154 // base within a constructor. If no viable function was
4155 // found, notify the user that she needs to explicitly
4156 // initialize this base/member.
4157 CXXConstructorDecl *Constructor
4158 = cast<CXXConstructorDecl>(S.CurContext);
4159 if (Entity.getKind() == InitializedEntity::EK_Base) {
4160 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4161 << Constructor->isImplicit()
4162 << S.Context.getTypeDeclType(Constructor->getParent())
4163 << /*base=*/0
4164 << Entity.getType();
4165
4166 RecordDecl *BaseDecl
4167 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4168 ->getDecl();
4169 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4170 << S.Context.getTagDeclType(BaseDecl);
4171 } else {
4172 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4173 << Constructor->isImplicit()
4174 << S.Context.getTypeDeclType(Constructor->getParent())
4175 << /*member=*/1
4176 << Entity.getName();
4177 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4178
4179 if (const RecordType *Record
4180 = Entity.getType()->getAs<RecordType>())
4181 S.Diag(Record->getDecl()->getLocation(),
4182 diag::note_previous_decl)
4183 << S.Context.getTagDeclType(Record->getDecl());
4184 }
4185 break;
4186 }
4187
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004188 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4189 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00004190 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4191 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004192 break;
4193
4194 case OR_Deleted: {
4195 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4196 << true << DestType << ArgsRange;
4197 OverloadCandidateSet::iterator Best;
4198 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4199 Kind.getLocation(),
4200 Best);
4201 if (Ovl == OR_Deleted) {
4202 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4203 << Best->Function->isDeleted();
4204 } else {
4205 llvm_unreachable("Inconsistent overload resolution?");
4206 }
4207 break;
4208 }
4209
4210 case OR_Success:
4211 llvm_unreachable("Conversion did not fail!");
4212 break;
4213 }
4214 break;
4215 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004216
4217 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004218 if (Entity.getKind() == InitializedEntity::EK_Member &&
4219 isa<CXXConstructorDecl>(S.CurContext)) {
4220 // This is implicit default-initialization of a const member in
4221 // a constructor. Complain that it needs to be explicitly
4222 // initialized.
4223 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4224 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4225 << Constructor->isImplicit()
4226 << S.Context.getTypeDeclType(Constructor->getParent())
4227 << /*const=*/1
4228 << Entity.getName();
4229 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4230 << Entity.getName();
4231 } else {
4232 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4233 << DestType << (bool)DestType->getAs<RecordType>();
4234 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004235 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004236
4237 case FK_Incomplete:
4238 S.RequireCompleteType(Kind.getLocation(), DestType,
4239 diag::err_init_incomplete_type);
4240 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 }
4242
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004243 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004244 return true;
4245}
Douglas Gregore1314a62009-12-18 05:02:21 +00004246
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004247void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4248 switch (SequenceKind) {
4249 case FailedSequence: {
4250 OS << "Failed sequence: ";
4251 switch (Failure) {
4252 case FK_TooManyInitsForReference:
4253 OS << "too many initializers for reference";
4254 break;
4255
4256 case FK_ArrayNeedsInitList:
4257 OS << "array requires initializer list";
4258 break;
4259
4260 case FK_ArrayNeedsInitListOrStringLiteral:
4261 OS << "array requires initializer list or string literal";
4262 break;
4263
4264 case FK_AddressOfOverloadFailed:
4265 OS << "address of overloaded function failed";
4266 break;
4267
4268 case FK_ReferenceInitOverloadFailed:
4269 OS << "overload resolution for reference initialization failed";
4270 break;
4271
4272 case FK_NonConstLValueReferenceBindingToTemporary:
4273 OS << "non-const lvalue reference bound to temporary";
4274 break;
4275
4276 case FK_NonConstLValueReferenceBindingToUnrelated:
4277 OS << "non-const lvalue reference bound to unrelated type";
4278 break;
4279
4280 case FK_RValueReferenceBindingToLValue:
4281 OS << "rvalue reference bound to an lvalue";
4282 break;
4283
4284 case FK_ReferenceInitDropsQualifiers:
4285 OS << "reference initialization drops qualifiers";
4286 break;
4287
4288 case FK_ReferenceInitFailed:
4289 OS << "reference initialization failed";
4290 break;
4291
4292 case FK_ConversionFailed:
4293 OS << "conversion failed";
4294 break;
4295
4296 case FK_TooManyInitsForScalar:
4297 OS << "too many initializers for scalar";
4298 break;
4299
4300 case FK_ReferenceBindingToInitList:
4301 OS << "referencing binding to initializer list";
4302 break;
4303
4304 case FK_InitListBadDestinationType:
4305 OS << "initializer list for non-aggregate, non-scalar type";
4306 break;
4307
4308 case FK_UserConversionOverloadFailed:
4309 OS << "overloading failed for user-defined conversion";
4310 break;
4311
4312 case FK_ConstructorOverloadFailed:
4313 OS << "constructor overloading failed";
4314 break;
4315
4316 case FK_DefaultInitOfConst:
4317 OS << "default initialization of a const variable";
4318 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004319
4320 case FK_Incomplete:
4321 OS << "initialization of incomplete type";
4322 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004323 }
4324 OS << '\n';
4325 return;
4326 }
4327
4328 case DependentSequence:
4329 OS << "Dependent sequence: ";
4330 return;
4331
4332 case UserDefinedConversion:
4333 OS << "User-defined conversion sequence: ";
4334 break;
4335
4336 case ConstructorInitialization:
4337 OS << "Constructor initialization sequence: ";
4338 break;
4339
4340 case ReferenceBinding:
4341 OS << "Reference binding: ";
4342 break;
4343
4344 case ListInitialization:
4345 OS << "List initialization: ";
4346 break;
4347
4348 case ZeroInitialization:
4349 OS << "Zero initialization\n";
4350 return;
4351
4352 case NoInitialization:
4353 OS << "No initialization\n";
4354 return;
4355
4356 case StandardConversion:
4357 OS << "Standard conversion: ";
4358 break;
4359
4360 case CAssignment:
4361 OS << "C assignment: ";
4362 break;
4363
4364 case StringInit:
4365 OS << "String initialization: ";
4366 break;
4367 }
4368
4369 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4370 if (S != step_begin()) {
4371 OS << " -> ";
4372 }
4373
4374 switch (S->Kind) {
4375 case SK_ResolveAddressOfOverloadedFunction:
4376 OS << "resolve address of overloaded function";
4377 break;
4378
4379 case SK_CastDerivedToBaseRValue:
4380 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4381 break;
4382
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004383 case SK_CastDerivedToBaseXValue:
4384 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4385 break;
4386
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004387 case SK_CastDerivedToBaseLValue:
4388 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4389 break;
4390
4391 case SK_BindReference:
4392 OS << "bind reference to lvalue";
4393 break;
4394
4395 case SK_BindReferenceToTemporary:
4396 OS << "bind reference to a temporary";
4397 break;
4398
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004399 case SK_ExtraneousCopyToTemporary:
4400 OS << "extraneous C++03 copy to temporary";
4401 break;
4402
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004403 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004404 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004405 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004406
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004407 case SK_QualificationConversionRValue:
4408 OS << "qualification conversion (rvalue)";
4409
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004410 case SK_QualificationConversionXValue:
4411 OS << "qualification conversion (xvalue)";
4412
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004413 case SK_QualificationConversionLValue:
4414 OS << "qualification conversion (lvalue)";
4415 break;
4416
4417 case SK_ConversionSequence:
4418 OS << "implicit conversion sequence (";
4419 S->ICS->DebugPrint(); // FIXME: use OS
4420 OS << ")";
4421 break;
4422
4423 case SK_ListInitialization:
4424 OS << "list initialization";
4425 break;
4426
4427 case SK_ConstructorInitialization:
4428 OS << "constructor initialization";
4429 break;
4430
4431 case SK_ZeroInitialization:
4432 OS << "zero initialization";
4433 break;
4434
4435 case SK_CAssignment:
4436 OS << "C assignment";
4437 break;
4438
4439 case SK_StringInit:
4440 OS << "string initialization";
4441 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004442
4443 case SK_ObjCObjectConversion:
4444 OS << "Objective-C object conversion";
4445 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004446 }
4447 }
4448}
4449
4450void InitializationSequence::dump() const {
4451 dump(llvm::errs());
4452}
4453
Douglas Gregore1314a62009-12-18 05:02:21 +00004454//===----------------------------------------------------------------------===//
4455// Initialization helper functions
4456//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004457ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004458Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4459 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004460 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004461 if (Init.isInvalid())
4462 return ExprError();
4463
4464 Expr *InitE = (Expr *)Init.get();
4465 assert(InitE && "No initialization expression?");
4466
4467 if (EqualLoc.isInvalid())
4468 EqualLoc = InitE->getLocStart();
4469
4470 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4471 EqualLoc);
4472 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4473 Init.release();
John McCall37ad5512010-08-23 06:44:23 +00004474 return Seq.Perform(*this, Entity, Kind, MultiExprArg(*this, &InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004475}