blob: 9130603d560575d49ffaf1b0b4da5df13e502154 [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattner79e079d2009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump1eb44332009-09-09 15:08:12 +000074
Chris Lattner79e079d2009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 }
Mike Stump1eb44332009-09-09 15:08:12 +000087
Eli Friedman8718a6a2009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000089
Eli Friedman8718a6a2009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000097
Eli Friedman8718a6a2009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000103}
104
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregor9e80f722009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000136namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000213
Douglas Gregord6d37de2009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner8b419b92009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000229
Douglas Gregord6d37de2009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
John McCall60d7b3a2010-08-24 06:29:42 +0000265 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000266 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000267 if (MemberInit.isInvalid()) {
268 hadError = true;
269 return;
270 }
271
272 if (hadError) {
273 // Do nothing
274 } else if (Init < NumInits) {
275 ILE->setInit(Init, MemberInit.takeAs<Expr>());
276 } else if (InitSeq.getKind()
277 == InitializationSequence::ConstructorInitialization) {
278 // Value-initialization requires a constructor call, so
279 // extend the initializer list to include the constructor
280 // call and make a note that we'll need to take another pass
281 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000282 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000283 RequiresSecondPass = true;
284 }
285 } else if (InitListExpr *InnerILE
286 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
287 FillInValueInitializations(MemberEntity, InnerILE,
288 RequiresSecondPass);
289}
290
Douglas Gregor4c678342009-01-28 21:54:33 +0000291/// Recursively replaces NULL values within the given initializer list
292/// with expressions that perform value-initialization of the
293/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000294void
295InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
296 InitListExpr *ILE,
297 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000298 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000299 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000300 SourceLocation Loc = ILE->getSourceRange().getBegin();
301 if (ILE->getSyntacticForm())
302 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Ted Kremenek6217b802009-07-29 21:53:49 +0000304 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000305 if (RType->getDecl()->isUnion() &&
306 ILE->getInitializedFieldInUnion())
307 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
308 Entity, ILE, RequiresSecondPass);
309 else {
310 unsigned Init = 0;
311 for (RecordDecl::field_iterator
312 Field = RType->getDecl()->field_begin(),
313 FieldEnd = RType->getDecl()->field_end();
314 Field != FieldEnd; ++Field) {
315 if (Field->isUnnamedBitfield())
316 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000317
Douglas Gregord6d37de2009-12-22 00:05:34 +0000318 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000319 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320
321 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
322 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000323 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000324
Douglas Gregord6d37de2009-12-22 00:05:34 +0000325 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 // Only look at the first initialization of a union.
328 if (RType->getDecl()->isUnion())
329 break;
330 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000331 }
332
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000335
336 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000338 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 unsigned NumInits = ILE->getNumInits();
340 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000341 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000342 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000343 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
344 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000345 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
346 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000347 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000348 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000349 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000350 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
351 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000352 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000353 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000355
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000357 if (hadError)
358 return;
359
Anders Carlssond3d824d2010-01-23 04:34:47 +0000360 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
361 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000362 ElementEntity.setElementIndex(Init);
363
Douglas Gregor87fd7032009-02-02 17:43:21 +0000364 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
366 true);
367 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
368 if (!InitSeq) {
369 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000370 hadError = true;
371 return;
372 }
373
John McCall60d7b3a2010-08-24 06:29:42 +0000374 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000375 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000376 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000377 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000378 return;
379 }
380
381 if (hadError) {
382 // Do nothing
383 } else if (Init < NumInits) {
384 ILE->setInit(Init, ElementInit.takeAs<Expr>());
385 } else if (InitSeq.getKind()
386 == InitializationSequence::ConstructorInitialization) {
387 // Value-initialization requires a constructor call, so
388 // extend the initializer list to include the constructor
389 // call and make a note that we'll need to take another pass
390 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000391 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000392 RequiresSecondPass = true;
393 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000394 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
396 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000397 }
398}
399
Chris Lattner68355a52009-01-29 05:10:57 +0000400
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
402 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000403 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000404 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000405
Eli Friedmanb85f7072008-05-19 19:16:24 +0000406 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000407 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000408 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000409 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000410 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000411 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000412 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000413
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000414 if (!hadError) {
415 bool RequiresSecondPass = false;
416 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000417 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 FillInValueInitializations(Entity, FullyStructuredList,
419 RequiresSecondPass);
420 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000421}
422
423int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000424 // FIXME: use a proper constant
425 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000426 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000427 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000428 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
429 }
430 return maxElements;
431}
432
433int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000434 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000435 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000436 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000437 Field = structDecl->field_begin(),
438 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000439 Field != FieldEnd; ++Field) {
440 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
441 ++InitializableMembers;
442 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000443 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000444 return std::min(InitializableMembers, 1);
445 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000446}
447
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000448void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000449 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000450 QualType T, unsigned &Index,
451 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000452 unsigned &StructuredIndex,
453 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000454 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Steve Naroff0cca7492008-05-01 22:18:59 +0000456 if (T->isArrayType())
457 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000458 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000460 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000461 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000462 else
463 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000464
Eli Friedman402256f2008-05-25 13:49:22 +0000465 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000466 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000467 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000469 hadError = true;
470 return;
471 }
472
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 // Build a structured initializer list corresponding to this subobject.
474 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000475 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
476 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000477 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
478 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000480
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000482 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000483 CheckListElementTypes(Entity, ParentIList, T,
484 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000485 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000486 StructuredSubobjectInitIndex,
487 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000488 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000489 StructuredSubobjectInitList->setType(T);
490
Douglas Gregored8a93d2009-03-01 17:12:46 +0000491 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000492 // range corresponds with the end of the last initializer it used.
493 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000494 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
496 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
497 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000498
499 // Warn about missing braces.
500 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000501 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
502 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000503 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000504 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
505 "{")
506 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000507 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000508 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000509 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000510}
511
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000512void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000513 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000518 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 SyntacticToSemantic[IList] = StructuredList;
520 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000521 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
522 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000523 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
524 IList->setType(ExprTy);
525 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000526 if (hadError)
527 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000528
Eli Friedman638e1442008-05-25 13:22:35 +0000529 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000531 if (StructuredIndex == 1 &&
532 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000533 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000534 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 hadError = true;
537 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000538 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000539 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000540 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000541 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000542 // Don't complain for incomplete types, since we'll get an error
543 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000544 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000545 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 CurrentObjectType->isArrayType()? 0 :
547 CurrentObjectType->isVectorType()? 1 :
548 CurrentObjectType->isScalarType()? 2 :
549 CurrentObjectType->isUnionType()? 3 :
550 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000551
552 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000553 if (SemaRef.getLangOptions().CPlusPlus) {
554 DK = diag::err_excess_initializers;
555 hadError = true;
556 }
Nate Begeman08634522009-07-07 21:53:06 +0000557 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000561
Chris Lattner08202542009-02-24 22:50:46 +0000562 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000563 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 }
565 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000566
Eli Friedman759f2522009-05-16 11:45:48 +0000567 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000568 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000569 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000570 << FixItHint::CreateRemoval(IList->getLocStart())
571 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000572}
573
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000574void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000575 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000576 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000577 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000578 unsigned &Index,
579 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000580 unsigned &StructuredIndex,
581 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000582 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000583 CheckScalarType(Entity, IList, DeclType, Index,
584 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000586 CheckVectorType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000588 } else if (DeclType->isAggregateType()) {
589 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000591 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000592 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000593 StructuredList, StructuredIndex,
594 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000595 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000596 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000597 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000599 CheckArrayType(Entity, IList, DeclType, Zero,
600 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000602 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000604 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
605 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000608 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000609 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000610 } else if (DeclType->isRecordType()) {
611 // C++ [dcl.init]p14:
612 // [...] If the class is an aggregate (8.5.1), and the initializer
613 // is a brace-enclosed list, see 8.5.1.
614 //
615 // Note: 8.5.1 is handled below; here, we diagnose the case where
616 // we have an initializer list and a destination type that is not
617 // an aggregate.
618 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000619 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000620 << DeclType << IList->getSourceRange();
621 hadError = true;
622 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000623 CheckReferenceType(Entity, IList, DeclType, Index,
624 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000625 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000626 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
627 << DeclType;
628 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000629 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
631 << DeclType;
632 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000633 }
634}
635
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000636void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000637 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000638 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned &Index,
640 InitListExpr *StructuredList,
641 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000642 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000643 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
644 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000645 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000646 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 = getStructuredSubobjectInit(IList, Index, ElemType,
648 StructuredList, StructuredIndex,
649 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000650 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000651 newStructuredList, newStructuredIndex);
652 ++StructuredIndex;
653 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000654 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
655 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000656 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000657 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000658 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000659 CheckScalarType(Entity, IList, ElemType, Index,
660 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000661 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000662 CheckReferenceType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000664 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000665 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 // C++ [dcl.init.aggr]p12:
667 // All implicit type conversions (clause 4) are considered when
668 // initializing the aggregate member with an ini- tializer from
669 // an initializer-list. If the initializer can initialize a
670 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000671
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000672 // FIXME: Better EqualLoc?
673 InitializationKind Kind =
674 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
675 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
676
677 if (Seq) {
John McCall60d7b3a2010-08-24 06:29:42 +0000678 ExprResult Result =
John McCallf312b1e2010-08-26 23:41:50 +0000679 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000680 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000681 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000682
683 UpdateStructuredListElement(StructuredList, StructuredIndex,
684 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 ++Index;
686 return;
687 }
688
689 // Fall through for subaggregate initialization
690 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000691 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000692 //
693 // The initializer for a structure or union object that has
694 // automatic storage duration shall be either an initializer
695 // list as described below, or a single expression that has
696 // compatible structure or union type. In the latter case, the
697 // initial value of the object, including unnamed members, is
698 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000699 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000700 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
John McCall74e40b72010-12-04 09:03:57 +0000701 SemaRef.DefaultFunctionArrayLvalueConversion(expr);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000702 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
703 ++Index;
704 return;
705 }
706
707 // Fall through for subaggregate initialization
708 }
709
710 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000711 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000712 // [...] Otherwise, if the member is itself a non-empty
713 // subaggregate, brace elision is assumed and the initializer is
714 // considered for the initialization of the first member of
715 // the subaggregate.
716 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000717 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000718 StructuredIndex);
719 ++StructuredIndex;
720 } else {
721 // We cannot initialize this element, so let
722 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000723 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
724 SemaRef.Owned(expr));
Douglas Gregor930d8b52009-01-30 22:09:00 +0000725 hadError = true;
726 ++Index;
727 ++StructuredIndex;
728 }
729 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000730}
731
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000732void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000733 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000734 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000735 InitListExpr *StructuredList,
736 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000737 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000738 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000739 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000740 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000741 ++Index;
742 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000743 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000744 }
John McCallb934c2d2010-11-11 00:46:36 +0000745
746 Expr *expr = IList->getInit(Index);
747 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
748 SemaRef.Diag(SubIList->getLocStart(),
749 diag::warn_many_braces_around_scalar_init)
750 << SubIList->getSourceRange();
751
752 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
753 StructuredIndex);
754 return;
755 } else if (isa<DesignatedInitExpr>(expr)) {
756 SemaRef.Diag(expr->getSourceRange().getBegin(),
757 diag::err_designator_for_scalar_init)
758 << DeclType << expr->getSourceRange();
759 hadError = true;
760 ++Index;
761 ++StructuredIndex;
762 return;
763 }
764
765 ExprResult Result =
766 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
767 SemaRef.Owned(expr));
768
769 Expr *ResultExpr = 0;
770
771 if (Result.isInvalid())
772 hadError = true; // types weren't compatible.
773 else {
774 ResultExpr = Result.takeAs<Expr>();
775
776 if (ResultExpr != expr) {
777 // The type was promoted, update initializer list.
778 IList->setInit(Index, ResultExpr);
779 }
780 }
781 if (hadError)
782 ++StructuredIndex;
783 else
784 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
785 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000786}
787
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000788void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
789 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000790 unsigned &Index,
791 InitListExpr *StructuredList,
792 unsigned &StructuredIndex) {
793 if (Index < IList->getNumInits()) {
794 Expr *expr = IList->getInit(Index);
795 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000796 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 << DeclType << IList->getSourceRange();
798 hadError = true;
799 ++Index;
800 ++StructuredIndex;
801 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000802 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000803
John McCall60d7b3a2010-08-24 06:29:42 +0000804 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000805 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
806 SemaRef.Owned(expr));
807
808 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000809 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000810
811 expr = Result.takeAs<Expr>();
812 IList->setInit(Index, expr);
813
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 if (hadError)
815 ++StructuredIndex;
816 else
817 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
818 ++Index;
819 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000820 // FIXME: It would be wonderful if we could point at the actual member. In
821 // general, it would be useful to pass location information down the stack,
822 // so that we know the location (or decl) of the "current object" being
823 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000824 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000825 diag::err_init_reference_member_uninitialized)
826 << DeclType
827 << IList->getSourceRange();
828 hadError = true;
829 ++Index;
830 ++StructuredIndex;
831 return;
832 }
833}
834
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000835void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000836 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000837 unsigned &Index,
838 InitListExpr *StructuredList,
839 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000840 if (Index >= IList->getNumInits())
841 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000842
John McCall20e047a2010-10-30 00:11:39 +0000843 const VectorType *VT = DeclType->getAs<VectorType>();
844 unsigned maxElements = VT->getNumElements();
845 unsigned numEltsInit = 0;
846 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000847
John McCall20e047a2010-10-30 00:11:39 +0000848 if (!SemaRef.getLangOptions().OpenCL) {
849 // If the initializing element is a vector, try to copy-initialize
850 // instead of breaking it apart (which is doomed to failure anyway).
851 Expr *Init = IList->getInit(Index);
852 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
853 ExprResult Result =
854 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
855 SemaRef.Owned(Init));
856
857 Expr *ResultExpr = 0;
858 if (Result.isInvalid())
859 hadError = true; // types weren't compatible.
860 else {
861 ResultExpr = Result.takeAs<Expr>();
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000862
John McCall20e047a2010-10-30 00:11:39 +0000863 if (ResultExpr != Init) {
864 // The type was promoted, update initializer list.
865 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000866 }
867 }
John McCall20e047a2010-10-30 00:11:39 +0000868 if (hadError)
869 ++StructuredIndex;
870 else
871 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
872 ++Index;
873 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
John McCall20e047a2010-10-30 00:11:39 +0000876 InitializedEntity ElementEntity =
877 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
878
879 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
880 // Don't attempt to go past the end of the init list
881 if (Index >= IList->getNumInits())
882 break;
883
884 ElementEntity.setElementIndex(Index);
885 CheckSubElementType(ElementEntity, IList, elementType, Index,
886 StructuredList, StructuredIndex);
887 }
888 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000889 }
John McCall20e047a2010-10-30 00:11:39 +0000890
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 // OpenCL initializers allows vectors to be constructed from vectors.
895 for (unsigned i = 0; i < maxElements; ++i) {
896 // Don't attempt to go past the end of the init list
897 if (Index >= IList->getNumInits())
898 break;
899
900 ElementEntity.setElementIndex(Index);
901
902 QualType IType = IList->getInit(Index)->getType();
903 if (!IType->isVectorType()) {
904 CheckSubElementType(ElementEntity, IList, elementType, Index,
905 StructuredList, StructuredIndex);
906 ++numEltsInit;
907 } else {
908 QualType VecType;
909 const VectorType *IVT = IType->getAs<VectorType>();
910 unsigned numIElts = IVT->getNumElements();
911
912 if (IType->isExtVectorType())
913 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
914 else
915 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000916 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000917 CheckSubElementType(ElementEntity, IList, VecType, Index,
918 StructuredList, StructuredIndex);
919 numEltsInit += numIElts;
920 }
921 }
922
923 // OpenCL requires all elements to be initialized.
924 if (numEltsInit != maxElements)
925 if (SemaRef.getLangOptions().OpenCL)
926 SemaRef.Diag(IList->getSourceRange().getBegin(),
927 diag::err_vector_incorrect_num_initializers)
928 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000929}
930
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000931void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000932 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000933 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000934 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000935 unsigned &Index,
936 InitListExpr *StructuredList,
937 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000938 // Check for the special-case of initializing an array with a string.
939 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000940 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
941 SemaRef.Context)) {
942 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000943 // We place the string literal directly into the resulting
944 // initializer list. This is the only place where the structure
945 // of the structured initializer list doesn't match exactly,
946 // because doing so would involve allocating one character
947 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000948 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000949 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000950 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000951 return;
952 }
953 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000954 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000955 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000956 // Check for VLAs; in standard C it would be possible to check this
957 // earlier, but I don't know where clang accepts VLAs (gcc accepts
958 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000959 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000960 diag::err_variable_object_no_init)
961 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000962 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000963 ++Index;
964 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000965 return;
966 }
967
Douglas Gregor05c13a32009-01-22 00:58:24 +0000968 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000969 llvm::APSInt maxElements(elementIndex.getBitWidth(),
970 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000971 bool maxElementsKnown = false;
972 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000973 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000974 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +0000975 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000976 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000977 maxElementsKnown = true;
978 }
979
Chris Lattner08202542009-02-24 22:50:46 +0000980 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000981 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000982 while (Index < IList->getNumInits()) {
983 Expr *Init = IList->getInit(Index);
984 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000985 // If we're not the subobject that matches up with the '{' for
986 // the designator, we shouldn't be handling the
987 // designator. Return immediately.
988 if (!SubobjectIsDesignatorContext)
989 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000990
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000991 // Handle this designated initializer. elementIndex will be
992 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000993 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000994 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000995 StructuredList, StructuredIndex, true,
996 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000997 hadError = true;
998 continue;
999 }
1000
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001001 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001002 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001003 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001004 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001005 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001006
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001007 // If the array is of incomplete type, keep track of the number of
1008 // elements in the initializer.
1009 if (!maxElementsKnown && elementIndex > maxElements)
1010 maxElements = elementIndex;
1011
Douglas Gregor05c13a32009-01-22 00:58:24 +00001012 continue;
1013 }
1014
1015 // If we know the maximum number of elements, and we've already
1016 // hit it, stop consuming elements in the initializer list.
1017 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001018 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001019
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001020 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +00001021 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001022 Entity);
1023 // Check this element.
1024 CheckSubElementType(ElementEntity, IList, elementType, Index,
1025 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001026 ++elementIndex;
1027
1028 // If the array is of incomplete type, keep track of the number of
1029 // elements in the initializer.
1030 if (!maxElementsKnown && elementIndex > maxElements)
1031 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001032 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001033 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001034 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001035 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001036 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001037 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001038 // Sizing an array implicitly to zero is not allowed by ISO C,
1039 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001040 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001041 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001042 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001043
Mike Stump1eb44332009-09-09 15:08:12 +00001044 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001045 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001046 }
1047}
1048
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001049void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001050 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001051 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001052 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001053 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001054 unsigned &Index,
1055 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001056 unsigned &StructuredIndex,
1057 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001058 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Eli Friedmanb85f7072008-05-19 19:16:24 +00001060 // If the record is invalid, some of it's members are invalid. To avoid
1061 // confusion, we forgo checking the intializer for the entire record.
1062 if (structDecl->isInvalidDecl()) {
1063 hadError = true;
1064 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001065 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001066
1067 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1068 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001069 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001070 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001071 Field != FieldEnd; ++Field) {
1072 if (Field->getDeclName()) {
1073 StructuredList->setInitializedFieldInUnion(*Field);
1074 break;
1075 }
1076 }
1077 return;
1078 }
1079
Douglas Gregor05c13a32009-01-22 00:58:24 +00001080 // If structDecl is a forward declaration, this loop won't do
1081 // anything except look at designated initializers; That's okay,
1082 // because an error should get printed out elsewhere. It might be
1083 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001084 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001085 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001086 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001087 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001088 while (Index < IList->getNumInits()) {
1089 Expr *Init = IList->getInit(Index);
1090
1091 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001092 // If we're not the subobject that matches up with the '{' for
1093 // the designator, we shouldn't be handling the
1094 // designator. Return immediately.
1095 if (!SubobjectIsDesignatorContext)
1096 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001097
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001098 // Handle this designated initializer. Field will be updated to
1099 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001100 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001101 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001102 StructuredList, StructuredIndex,
1103 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001104 hadError = true;
1105
Douglas Gregordfb5e592009-02-12 19:00:39 +00001106 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001107
1108 // Disable check for missing fields when designators are used.
1109 // This matches gcc behaviour.
1110 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001111 continue;
1112 }
1113
1114 if (Field == FieldEnd) {
1115 // We've run out of fields. We're done.
1116 break;
1117 }
1118
Douglas Gregordfb5e592009-02-12 19:00:39 +00001119 // We've already initialized a member of a union. We're done.
1120 if (InitializedSomething && DeclType->isUnionType())
1121 break;
1122
Douglas Gregor44b43212008-12-11 16:49:14 +00001123 // If we've hit the flexible array member at the end, we're done.
1124 if (Field->getType()->isIncompleteArrayType())
1125 break;
1126
Douglas Gregor0bb76892009-01-29 16:53:55 +00001127 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001128 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001129 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001130 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001131 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001132
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001133 InitializedEntity MemberEntity =
1134 InitializedEntity::InitializeMember(*Field, &Entity);
1135 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1136 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001137 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001138
1139 if (DeclType->isUnionType()) {
1140 // Initialize the first field within the union.
1141 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001142 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001143
1144 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001145 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001146
John McCall80639de2010-03-11 19:32:38 +00001147 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001148 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001149 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1150 // It is possible we have one or more unnamed bitfields remaining.
1151 // Find first (if any) named field and emit warning.
1152 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1153 it != end; ++it) {
1154 if (!it->isUnnamedBitfield()) {
1155 SemaRef.Diag(IList->getSourceRange().getEnd(),
1156 diag::warn_missing_field_initializers) << it->getName();
1157 break;
1158 }
1159 }
1160 }
1161
Mike Stump1eb44332009-09-09 15:08:12 +00001162 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001163 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001164 return;
1165
1166 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001167 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001168 (!isa<InitListExpr>(IList->getInit(Index)) ||
1169 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001170 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001171 diag::err_flexible_array_init_nonempty)
1172 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001173 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001174 << *Field;
1175 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001176 ++Index;
1177 return;
1178 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001179 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001180 diag::ext_flexible_array_init)
1181 << IList->getInit(Index)->getSourceRange().getBegin();
1182 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1183 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001184 }
1185
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001186 InitializedEntity MemberEntity =
1187 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001188
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001189 if (isa<InitListExpr>(IList->getInit(Index)))
1190 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1191 StructuredList, StructuredIndex);
1192 else
1193 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001194 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001195}
Steve Naroff0cca7492008-05-01 22:18:59 +00001196
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001197/// \brief Expand a field designator that refers to a member of an
1198/// anonymous struct or union into a series of field designators that
1199/// refers to the field within the appropriate subobject.
1200///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001201static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001202 DesignatedInitExpr *DIE,
1203 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001204 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001205 typedef DesignatedInitExpr::Designator Designator;
1206
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001207 // Build the replacement designators.
1208 llvm::SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001209 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1210 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1211 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001212 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001213 DIE->getDesignator(DesigIdx)->getDotLoc(),
1214 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1215 else
1216 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1217 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001218 assert(isa<FieldDecl>(*PI));
1219 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001220 }
1221
1222 // Expand the current designator into the set of replacement
1223 // designators, so we have a full subobject path down to where the
1224 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001225 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001226 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001227}
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Francois Picheta0e27f02010-12-22 03:46:10 +00001229/// \brief Given an implicit anonymous field, search the IndirectField that
1230/// corresponds to FieldName.
1231static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1232 IdentifierInfo *FieldName) {
1233 assert(AnonField->isAnonymousStructOrUnion());
1234 Decl *NextDecl = AnonField->getNextDeclInContext();
1235 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1236 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1237 return IF;
1238 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001239 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001240 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001241}
1242
Douglas Gregor05c13a32009-01-22 00:58:24 +00001243/// @brief Check the well-formedness of a C99 designated initializer.
1244///
1245/// Determines whether the designated initializer @p DIE, which
1246/// resides at the given @p Index within the initializer list @p
1247/// IList, is well-formed for a current object of type @p DeclType
1248/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001249/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001250/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001251///
1252/// @param IList The initializer list in which this designated
1253/// initializer occurs.
1254///
Douglas Gregor71199712009-04-15 04:56:10 +00001255/// @param DIE The designated initializer expression.
1256///
1257/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001258///
1259/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1260/// into which the designation in @p DIE should refer.
1261///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001262/// @param NextField If non-NULL and the first designator in @p DIE is
1263/// a field, this will be set to the field declaration corresponding
1264/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001265///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001266/// @param NextElementIndex If non-NULL and the first designator in @p
1267/// DIE is an array designator or GNU array-range designator, this
1268/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001269///
1270/// @param Index Index into @p IList where the designated initializer
1271/// @p DIE occurs.
1272///
Douglas Gregor4c678342009-01-28 21:54:33 +00001273/// @param StructuredList The initializer list expression that
1274/// describes all of the subobject initializers in the order they'll
1275/// actually be initialized.
1276///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001277/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001278bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001279InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001280 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001281 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001282 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001283 QualType &CurrentObjectType,
1284 RecordDecl::field_iterator *NextField,
1285 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001286 unsigned &Index,
1287 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001288 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001289 bool FinishSubobjectInit,
1290 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001291 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001292 // Check the actual initialization for the designated object type.
1293 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001294
1295 // Temporarily remove the designator expression from the
1296 // initializer list that the child calls see, so that we don't try
1297 // to re-process the designator.
1298 unsigned OldIndex = Index;
1299 IList->setInit(OldIndex, DIE->getInit());
1300
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001301 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001302 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001303
1304 // Restore the designated initializer expression in the syntactic
1305 // form of the initializer list.
1306 if (IList->getInit(OldIndex) != DIE->getInit())
1307 DIE->setInit(IList->getInit(OldIndex));
1308 IList->setInit(OldIndex, DIE);
1309
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001310 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001311 }
1312
Douglas Gregor71199712009-04-15 04:56:10 +00001313 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001314 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 "Need a non-designated initializer list to start from");
1316
Douglas Gregor71199712009-04-15 04:56:10 +00001317 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 // Determine the structural initializer list that corresponds to the
1319 // current subobject.
1320 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001321 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001322 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001323 SourceRange(D->getStartLocation(),
1324 DIE->getSourceRange().getEnd()));
1325 assert(StructuredList && "Expected a structured initializer list");
1326
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001327 if (D->isFieldDesignator()) {
1328 // C99 6.7.8p7:
1329 //
1330 // If a designator has the form
1331 //
1332 // . identifier
1333 //
1334 // then the current object (defined below) shall have
1335 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001336 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001337 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001338 if (!RT) {
1339 SourceLocation Loc = D->getDotLoc();
1340 if (Loc.isInvalid())
1341 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001342 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1343 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001344 ++Index;
1345 return true;
1346 }
1347
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 // Note: we perform a linear search of the fields here, despite
1349 // the fact that we have a faster lookup method, because we always
1350 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001351 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001352 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001353 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001354 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001355 Field = RT->getDecl()->field_begin(),
1356 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001357 for (; Field != FieldEnd; ++Field) {
1358 if (Field->isUnnamedBitfield())
1359 continue;
Francois Picheta0e27f02010-12-22 03:46:10 +00001360
1361 // If we find a field representing an anonymous field, look in the
1362 // IndirectFieldDecl that follow for the designated initializer.
1363 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1364 if (IndirectFieldDecl *IF =
1365 FindIndirectFieldDesignator(*Field, FieldName)) {
1366 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1367 D = DIE->getDesignator(DesigIdx);
1368 break;
1369 }
1370 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001371 if (KnownField && KnownField == *Field)
1372 break;
1373 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001374 break;
1375
1376 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001377 }
1378
Douglas Gregor4c678342009-01-28 21:54:33 +00001379 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001380 // There was no normal field in the struct with the designated
1381 // name. Perform another lookup for this name, which may find
1382 // something that we can't designate (e.g., a member function),
1383 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001384 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001385 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001386 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001387 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001388 // Name lookup didn't find anything. Determine whether this
1389 // was a typo for another field name.
1390 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1391 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001392 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1393 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001394 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001395 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001396 ->Equals(RT->getDecl())) {
1397 SemaRef.Diag(D->getFieldLoc(),
1398 diag::err_field_designator_unknown_suggest)
1399 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001400 << FixItHint::CreateReplacement(D->getFieldLoc(),
1401 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001402 SemaRef.Diag(ReplacementField->getLocation(),
1403 diag::note_previous_decl)
1404 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001405 } else {
1406 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1407 << FieldName << CurrentObjectType;
1408 ++Index;
1409 return true;
1410 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001411 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001412
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001413 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001414 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001415 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001416 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001417 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001418 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001419 ++Index;
1420 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001421 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001422
Francois Picheta0e27f02010-12-22 03:46:10 +00001423 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001424 // The replacement field comes from typo correction; find it
1425 // in the list of fields.
1426 FieldIndex = 0;
1427 Field = RT->getDecl()->field_begin();
1428 for (; Field != FieldEnd; ++Field) {
1429 if (Field->isUnnamedBitfield())
1430 continue;
1431
1432 if (ReplacementField == *Field ||
1433 Field->getIdentifier() == ReplacementField->getIdentifier())
1434 break;
1435
1436 ++FieldIndex;
1437 }
1438 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001439 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001440
1441 // All of the fields of a union are located at the same place in
1442 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001443 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001444 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001445 StructuredList->setInitializedFieldInUnion(*Field);
1446 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001447
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001448 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001449 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregor4c678342009-01-28 21:54:33 +00001451 // Make sure that our non-designated initializer list has space
1452 // for a subobject corresponding to this field.
1453 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001454 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001455
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 // This designator names a flexible array member.
1457 if (Field->getType()->isIncompleteArrayType()) {
1458 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001459 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 // We can't designate an object within the flexible array
1461 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001462 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001463 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001464 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001465 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001466 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001467 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001468 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001469 << *Field;
1470 Invalid = true;
1471 }
1472
Chris Lattner9046c222010-10-10 17:49:49 +00001473 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1474 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001475 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001476 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001477 diag::err_flexible_array_init_needs_braces)
1478 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001479 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001480 << *Field;
1481 Invalid = true;
1482 }
1483
1484 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001485 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001486 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001487 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001488 diag::err_flexible_array_init_nonempty)
1489 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001490 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 << *Field;
1492 Invalid = true;
1493 }
1494
1495 if (Invalid) {
1496 ++Index;
1497 return true;
1498 }
1499
1500 // Initialize the array.
1501 bool prevHadError = hadError;
1502 unsigned newStructuredIndex = FieldIndex;
1503 unsigned OldIndex = Index;
1504 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001505
1506 InitializedEntity MemberEntity =
1507 InitializedEntity::InitializeMember(*Field, &Entity);
1508 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001509 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001510
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001511 IList->setInit(OldIndex, DIE);
1512 if (hadError && !prevHadError) {
1513 ++Field;
1514 ++FieldIndex;
1515 if (NextField)
1516 *NextField = Field;
1517 StructuredIndex = FieldIndex;
1518 return true;
1519 }
1520 } else {
1521 // Recurse to check later designated subobjects.
1522 QualType FieldType = (*Field)->getType();
1523 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001524
1525 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001526 InitializedEntity::InitializeMember(*Field, &Entity);
1527 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001528 FieldType, 0, 0, Index,
1529 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001530 true, false))
1531 return true;
1532 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001533
1534 // Find the position of the next field to be initialized in this
1535 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001536 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001537 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001538
1539 // If this the first designator, our caller will continue checking
1540 // the rest of this struct/class/union subobject.
1541 if (IsFirstDesignator) {
1542 if (NextField)
1543 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001544 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001545 return false;
1546 }
1547
Douglas Gregor34e79462009-01-28 23:36:17 +00001548 if (!FinishSubobjectInit)
1549 return false;
1550
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001551 // We've already initialized something in the union; we're done.
1552 if (RT->getDecl()->isUnion())
1553 return hadError;
1554
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001555 // Check the remaining fields within this class/struct/union subobject.
1556 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001557
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001558 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001559 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001560 return hadError && !prevHadError;
1561 }
1562
1563 // C99 6.7.8p6:
1564 //
1565 // If a designator has the form
1566 //
1567 // [ constant-expression ]
1568 //
1569 // then the current object (defined below) shall have array
1570 // type and the expression shall be an integer constant
1571 // expression. If the array is of unknown size, any
1572 // nonnegative value is valid.
1573 //
1574 // Additionally, cope with the GNU extension that permits
1575 // designators of the form
1576 //
1577 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001578 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001579 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001580 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 << CurrentObjectType;
1582 ++Index;
1583 return true;
1584 }
1585
1586 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001587 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1588 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001589 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001590 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001591 DesignatedEndIndex = DesignatedStartIndex;
1592 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001593 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001594
Mike Stump1eb44332009-09-09 15:08:12 +00001595
1596 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001597 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001598 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001599 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001600 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001601
Chris Lattner3bf68932009-04-25 21:59:05 +00001602 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001603 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001604 }
1605
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001606 if (isa<ConstantArrayType>(AT)) {
1607 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001608 DesignatedStartIndex
1609 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001610 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001611 DesignatedEndIndex
1612 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001613 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1614 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001615 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001616 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001617 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001618 << IndexExpr->getSourceRange();
1619 ++Index;
1620 return true;
1621 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001622 } else {
1623 // Make sure the bit-widths and signedness match.
1624 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001625 DesignatedEndIndex
1626 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001627 else if (DesignatedStartIndex.getBitWidth() <
1628 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001629 DesignatedStartIndex
1630 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001631 DesignatedStartIndex.setIsUnsigned(true);
1632 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001633 }
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Douglas Gregor4c678342009-01-28 21:54:33 +00001635 // Make sure that our non-designated initializer list has space
1636 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001637 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001638 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001639 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001640
Douglas Gregor34e79462009-01-28 23:36:17 +00001641 // Repeatedly perform subobject initializations in the range
1642 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643
Douglas Gregor34e79462009-01-28 23:36:17 +00001644 // Move to the next designator
1645 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1646 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001647
1648 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001649 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001650
Douglas Gregor34e79462009-01-28 23:36:17 +00001651 while (DesignatedStartIndex <= DesignatedEndIndex) {
1652 // Recurse to check later designated subobjects.
1653 QualType ElementType = AT->getElementType();
1654 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001655
1656 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001657 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001658 ElementType, 0, 0, Index,
1659 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001660 (DesignatedStartIndex == DesignatedEndIndex),
1661 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001662 return true;
1663
1664 // Move to the next index in the array that we'll be initializing.
1665 ++DesignatedStartIndex;
1666 ElementIndex = DesignatedStartIndex.getZExtValue();
1667 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001668
1669 // If this the first designator, our caller will continue checking
1670 // the rest of this array subobject.
1671 if (IsFirstDesignator) {
1672 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001673 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001674 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001675 return false;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Douglas Gregor34e79462009-01-28 23:36:17 +00001678 if (!FinishSubobjectInit)
1679 return false;
1680
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001681 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001682 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001683 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001684 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001685 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001686 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001687}
1688
Douglas Gregor4c678342009-01-28 21:54:33 +00001689// Get the structured initializer list for a subobject of type
1690// @p CurrentObjectType.
1691InitListExpr *
1692InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1693 QualType CurrentObjectType,
1694 InitListExpr *StructuredList,
1695 unsigned StructuredIndex,
1696 SourceRange InitRange) {
1697 Expr *ExistingInit = 0;
1698 if (!StructuredList)
1699 ExistingInit = SyntacticToSemantic[IList];
1700 else if (StructuredIndex < StructuredList->getNumInits())
1701 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor4c678342009-01-28 21:54:33 +00001703 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1704 return Result;
1705
1706 if (ExistingInit) {
1707 // We are creating an initializer list that initializes the
1708 // subobjects of the current object, but there was already an
1709 // initialization that completely initialized the current
1710 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001711 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001712 // struct X { int a, b; };
1713 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001714 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001715 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1716 // designated initializer re-initializes the whole
1717 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001718 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001719 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001720 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001721 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001722 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001723 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001724 << ExistingInit->getSourceRange();
1725 }
1726
Mike Stump1eb44332009-09-09 15:08:12 +00001727 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001728 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1729 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001730 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001731
Douglas Gregor63982352010-07-13 18:40:04 +00001732 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001733
Douglas Gregorfa219202009-03-20 23:58:33 +00001734 // Pre-allocate storage for the structured initializer list.
1735 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001736 unsigned NumInits = 0;
1737 if (!StructuredList)
1738 NumInits = IList->getNumInits();
1739 else if (Index < IList->getNumInits()) {
1740 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1741 NumInits = SubList->getNumInits();
1742 }
1743
Mike Stump1eb44332009-09-09 15:08:12 +00001744 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001745 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1746 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1747 NumElements = CAType->getSize().getZExtValue();
1748 // Simple heuristic so that we don't allocate a very large
1749 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001750 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001751 NumElements = 0;
1752 }
John McCall183700f2009-09-21 23:43:11 +00001753 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001754 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001755 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001756 RecordDecl *RDecl = RType->getDecl();
1757 if (RDecl->isUnion())
1758 NumElements = 1;
1759 else
Mike Stump1eb44332009-09-09 15:08:12 +00001760 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001761 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001762 }
1763
Douglas Gregor08457732009-03-21 18:13:52 +00001764 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001765 NumElements = IList->getNumInits();
1766
Ted Kremenek709210f2010-04-13 23:39:13 +00001767 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001768
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 // Link this new initializer list into the structured initializer
1770 // lists.
1771 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001772 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001773 else {
1774 Result->setSyntacticForm(IList);
1775 SyntacticToSemantic[IList] = Result;
1776 }
1777
1778 return Result;
1779}
1780
1781/// Update the initializer at index @p StructuredIndex within the
1782/// structured initializer list to the value @p expr.
1783void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1784 unsigned &StructuredIndex,
1785 Expr *expr) {
1786 // No structured initializer list to update
1787 if (!StructuredList)
1788 return;
1789
Ted Kremenek709210f2010-04-13 23:39:13 +00001790 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1791 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001792 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001793 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001794 diag::warn_initializer_overrides)
1795 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001796 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001798 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 << PrevInit->getSourceRange();
1800 }
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregor4c678342009-01-28 21:54:33 +00001802 ++StructuredIndex;
1803}
1804
Douglas Gregor05c13a32009-01-22 00:58:24 +00001805/// Check that the given Index expression is a valid array designator
1806/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001807/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001808/// and produces a reasonable diagnostic if there is a
1809/// failure. Returns true if there was an error, false otherwise. If
1810/// everything went okay, Value will receive the value of the constant
1811/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001812static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001813CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001814 SourceLocation Loc = Index->getSourceRange().getBegin();
1815
1816 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001817 if (S.VerifyIntegerConstantExpression(Index, &Value))
1818 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001819
Chris Lattner3bf68932009-04-25 21:59:05 +00001820 if (Value.isSigned() && Value.isNegative())
1821 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001822 << Value.toString(10) << Index->getSourceRange();
1823
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001824 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001825 return false;
1826}
1827
John McCall60d7b3a2010-08-24 06:29:42 +00001828ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001829 SourceLocation Loc,
1830 bool GNUSyntax,
1831 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001832 typedef DesignatedInitExpr::Designator ASTDesignator;
1833
1834 bool Invalid = false;
1835 llvm::SmallVector<ASTDesignator, 32> Designators;
1836 llvm::SmallVector<Expr *, 32> InitExpressions;
1837
1838 // Build designators and check array designator expressions.
1839 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1840 const Designator &D = Desig.getDesignator(Idx);
1841 switch (D.getKind()) {
1842 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001843 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001844 D.getFieldLoc()));
1845 break;
1846
1847 case Designator::ArrayDesignator: {
1848 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1849 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001850 if (!Index->isTypeDependent() &&
1851 !Index->isValueDependent() &&
1852 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001853 Invalid = true;
1854 else {
1855 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001856 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001857 D.getRBracketLoc()));
1858 InitExpressions.push_back(Index);
1859 }
1860 break;
1861 }
1862
1863 case Designator::ArrayRangeDesignator: {
1864 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1865 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1866 llvm::APSInt StartValue;
1867 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001868 bool StartDependent = StartIndex->isTypeDependent() ||
1869 StartIndex->isValueDependent();
1870 bool EndDependent = EndIndex->isTypeDependent() ||
1871 EndIndex->isValueDependent();
1872 if ((!StartDependent &&
1873 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1874 (!EndDependent &&
1875 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001876 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001877 else {
1878 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001879 if (StartDependent || EndDependent) {
1880 // Nothing to compute.
1881 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001882 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001883 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001884 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001885
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001886 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001887 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001888 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001889 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1890 Invalid = true;
1891 } else {
1892 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001893 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001894 D.getEllipsisLoc(),
1895 D.getRBracketLoc()));
1896 InitExpressions.push_back(StartIndex);
1897 InitExpressions.push_back(EndIndex);
1898 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001899 }
1900 break;
1901 }
1902 }
1903 }
1904
1905 if (Invalid || Init.isInvalid())
1906 return ExprError();
1907
1908 // Clear out the expressions within the designation.
1909 Desig.ClearExprs(*this);
1910
1911 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001912 = DesignatedInitExpr::Create(Context,
1913 Designators.data(), Designators.size(),
1914 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001915 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001916
1917 if (getLangOptions().CPlusPlus)
1918 Diag(DIE->getLocStart(), diag::ext_designated_init)
1919 << DIE->getSourceRange();
1920
Douglas Gregor05c13a32009-01-22 00:58:24 +00001921 return Owned(DIE);
1922}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001923
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001924bool Sema::CheckInitList(const InitializedEntity &Entity,
1925 InitListExpr *&InitList, QualType &DeclType) {
1926 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001927 if (!CheckInitList.HadError())
1928 InitList = CheckInitList.getFullyStructuredList();
1929
1930 return CheckInitList.HadError();
1931}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001932
Douglas Gregor20093b42009-12-09 23:02:17 +00001933//===----------------------------------------------------------------------===//
1934// Initialization entity
1935//===----------------------------------------------------------------------===//
1936
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001937InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1938 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001939 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001940{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001941 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1942 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001943 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001944 } else {
1945 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001946 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001947 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001948}
1949
1950InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001951 CXXBaseSpecifier *Base,
1952 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001953{
1954 InitializedEntity Result;
1955 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001956 Result.Base = reinterpret_cast<uintptr_t>(Base);
1957 if (IsInheritedVirtualBase)
1958 Result.Base |= 0x01;
1959
Douglas Gregord6542d82009-12-22 15:35:07 +00001960 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001961 return Result;
1962}
1963
Douglas Gregor99a2e602009-12-16 01:38:02 +00001964DeclarationName InitializedEntity::getName() const {
1965 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001966 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001967 if (!VariableOrMember)
1968 return DeclarationName();
1969 // Fall through
1970
1971 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001972 case EK_Member:
1973 return VariableOrMember->getDeclName();
1974
1975 case EK_Result:
1976 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001977 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001978 case EK_Temporary:
1979 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001980 case EK_ArrayElement:
1981 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001982 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001983 return DeclarationName();
1984 }
1985
1986 // Silence GCC warning
1987 return DeclarationName();
1988}
1989
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001990DeclaratorDecl *InitializedEntity::getDecl() const {
1991 switch (getKind()) {
1992 case EK_Variable:
1993 case EK_Parameter:
1994 case EK_Member:
1995 return VariableOrMember;
1996
1997 case EK_Result:
1998 case EK_Exception:
1999 case EK_New:
2000 case EK_Temporary:
2001 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002002 case EK_ArrayElement:
2003 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002004 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002005 return 0;
2006 }
2007
2008 // Silence GCC warning
2009 return 0;
2010}
2011
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002012bool InitializedEntity::allowsNRVO() const {
2013 switch (getKind()) {
2014 case EK_Result:
2015 case EK_Exception:
2016 return LocAndNRVO.NRVO;
2017
2018 case EK_Variable:
2019 case EK_Parameter:
2020 case EK_Member:
2021 case EK_New:
2022 case EK_Temporary:
2023 case EK_Base:
2024 case EK_ArrayElement:
2025 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002026 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002027 break;
2028 }
2029
2030 return false;
2031}
2032
Douglas Gregor20093b42009-12-09 23:02:17 +00002033//===----------------------------------------------------------------------===//
2034// Initialization sequence
2035//===----------------------------------------------------------------------===//
2036
2037void InitializationSequence::Step::Destroy() {
2038 switch (Kind) {
2039 case SK_ResolveAddressOfOverloadedFunction:
2040 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002041 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002042 case SK_CastDerivedToBaseLValue:
2043 case SK_BindReference:
2044 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002045 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002046 case SK_UserConversion:
2047 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002048 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002049 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002050 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002051 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002052 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002053 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002054 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002055 case SK_ObjCObjectConversion:
Douglas Gregor20093b42009-12-09 23:02:17 +00002056 break;
2057
2058 case SK_ConversionSequence:
2059 delete ICS;
2060 }
2061}
2062
Douglas Gregorb70cf442010-03-26 20:14:36 +00002063bool InitializationSequence::isDirectReferenceBinding() const {
2064 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2065}
2066
2067bool InitializationSequence::isAmbiguous() const {
2068 if (getKind() != FailedSequence)
2069 return false;
2070
2071 switch (getFailureKind()) {
2072 case FK_TooManyInitsForReference:
2073 case FK_ArrayNeedsInitList:
2074 case FK_ArrayNeedsInitListOrStringLiteral:
2075 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2076 case FK_NonConstLValueReferenceBindingToTemporary:
2077 case FK_NonConstLValueReferenceBindingToUnrelated:
2078 case FK_RValueReferenceBindingToLValue:
2079 case FK_ReferenceInitDropsQualifiers:
2080 case FK_ReferenceInitFailed:
2081 case FK_ConversionFailed:
2082 case FK_TooManyInitsForScalar:
2083 case FK_ReferenceBindingToInitList:
2084 case FK_InitListBadDestinationType:
2085 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002086 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002087 return false;
2088
2089 case FK_ReferenceInitOverloadFailed:
2090 case FK_UserConversionOverloadFailed:
2091 case FK_ConstructorOverloadFailed:
2092 return FailedOverloadResult == OR_Ambiguous;
2093 }
2094
2095 return false;
2096}
2097
Douglas Gregord6e44a32010-04-16 22:09:46 +00002098bool InitializationSequence::isConstructorInitialization() const {
2099 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2100}
2101
Douglas Gregor20093b42009-12-09 23:02:17 +00002102void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002103 FunctionDecl *Function,
2104 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002105 Step S;
2106 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2107 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002108 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002109 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002110 Steps.push_back(S);
2111}
2112
2113void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002114 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002115 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002116 switch (VK) {
2117 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2118 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2119 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002120 default: llvm_unreachable("No such category");
2121 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002122 S.Type = BaseType;
2123 Steps.push_back(S);
2124}
2125
2126void InitializationSequence::AddReferenceBindingStep(QualType T,
2127 bool BindingTemporary) {
2128 Step S;
2129 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2130 S.Type = T;
2131 Steps.push_back(S);
2132}
2133
Douglas Gregor523d46a2010-04-18 07:40:54 +00002134void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2135 Step S;
2136 S.Kind = SK_ExtraneousCopyToTemporary;
2137 S.Type = T;
2138 Steps.push_back(S);
2139}
2140
Eli Friedman03981012009-12-11 02:42:07 +00002141void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002142 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002143 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002144 Step S;
2145 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002146 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002147 S.Function.Function = Function;
2148 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002149 Steps.push_back(S);
2150}
2151
2152void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002153 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002154 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002155 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002156 switch (VK) {
2157 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002158 S.Kind = SK_QualificationConversionRValue;
2159 break;
John McCall5baba9d2010-08-25 10:28:54 +00002160 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002161 S.Kind = SK_QualificationConversionXValue;
2162 break;
John McCall5baba9d2010-08-25 10:28:54 +00002163 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002164 S.Kind = SK_QualificationConversionLValue;
2165 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002166 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002167 S.Type = Ty;
2168 Steps.push_back(S);
2169}
2170
2171void InitializationSequence::AddConversionSequenceStep(
2172 const ImplicitConversionSequence &ICS,
2173 QualType T) {
2174 Step S;
2175 S.Kind = SK_ConversionSequence;
2176 S.Type = T;
2177 S.ICS = new ImplicitConversionSequence(ICS);
2178 Steps.push_back(S);
2179}
2180
Douglas Gregord87b61f2009-12-10 17:56:55 +00002181void InitializationSequence::AddListInitializationStep(QualType T) {
2182 Step S;
2183 S.Kind = SK_ListInitialization;
2184 S.Type = T;
2185 Steps.push_back(S);
2186}
2187
Douglas Gregor51c56d62009-12-14 20:49:26 +00002188void
2189InitializationSequence::AddConstructorInitializationStep(
2190 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002191 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002192 QualType T) {
2193 Step S;
2194 S.Kind = SK_ConstructorInitialization;
2195 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002196 S.Function.Function = Constructor;
2197 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002198 Steps.push_back(S);
2199}
2200
Douglas Gregor71d17402009-12-15 00:01:57 +00002201void InitializationSequence::AddZeroInitializationStep(QualType T) {
2202 Step S;
2203 S.Kind = SK_ZeroInitialization;
2204 S.Type = T;
2205 Steps.push_back(S);
2206}
2207
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002208void InitializationSequence::AddCAssignmentStep(QualType T) {
2209 Step S;
2210 S.Kind = SK_CAssignment;
2211 S.Type = T;
2212 Steps.push_back(S);
2213}
2214
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002215void InitializationSequence::AddStringInitStep(QualType T) {
2216 Step S;
2217 S.Kind = SK_StringInit;
2218 S.Type = T;
2219 Steps.push_back(S);
2220}
2221
Douglas Gregor569c3162010-08-07 11:51:51 +00002222void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2223 Step S;
2224 S.Kind = SK_ObjCObjectConversion;
2225 S.Type = T;
2226 Steps.push_back(S);
2227}
2228
Douglas Gregor20093b42009-12-09 23:02:17 +00002229void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2230 OverloadingResult Result) {
2231 SequenceKind = FailedSequence;
2232 this->Failure = Failure;
2233 this->FailedOverloadResult = Result;
2234}
2235
2236//===----------------------------------------------------------------------===//
2237// Attempt initialization
2238//===----------------------------------------------------------------------===//
2239
2240/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002241static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002242 const InitializedEntity &Entity,
2243 const InitializationKind &Kind,
2244 InitListExpr *InitList,
2245 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002246 // FIXME: We only perform rudimentary checking of list
2247 // initializations at this point, then assume that any list
2248 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002249 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002250 // do all of the necessary checking. C++0x initializer lists will
2251 // force us to perform more checking here.
2252 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2253
Douglas Gregord6542d82009-12-22 15:35:07 +00002254 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002255
2256 // C++ [dcl.init]p13:
2257 // If T is a scalar type, then a declaration of the form
2258 //
2259 // T x = { a };
2260 //
2261 // is equivalent to
2262 //
2263 // T x = a;
2264 if (DestType->isScalarType()) {
2265 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2266 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2267 return;
2268 }
2269
2270 // Assume scalar initialization from a single value works.
2271 } else if (DestType->isAggregateType()) {
2272 // Assume aggregate initialization works.
2273 } else if (DestType->isVectorType()) {
2274 // Assume vector initialization works.
2275 } else if (DestType->isReferenceType()) {
2276 // FIXME: C++0x defines behavior for this.
2277 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2278 return;
2279 } else if (DestType->isRecordType()) {
2280 // FIXME: C++0x defines behavior for this
2281 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2282 }
2283
2284 // Add a general "list initialization" step.
2285 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002286}
2287
2288/// \brief Try a reference initialization that involves calling a conversion
2289/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002290static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2291 const InitializedEntity &Entity,
2292 const InitializationKind &Kind,
2293 Expr *Initializer,
2294 bool AllowRValues,
2295 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002296 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002297 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2298 QualType T1 = cv1T1.getUnqualifiedType();
2299 QualType cv2T2 = Initializer->getType();
2300 QualType T2 = cv2T2.getUnqualifiedType();
2301
2302 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002303 bool ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002305 T1, T2, DerivedToBase,
2306 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002307 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002308 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002309 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002310
2311 // Build the candidate set directly in the initialization sequence
2312 // structure, so that it will persist if we fail.
2313 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2314 CandidateSet.clear();
2315
2316 // Determine whether we are allowed to call explicit constructors or
2317 // explicit conversion operators.
2318 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2319
2320 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002321 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2322 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002323 // The type we're converting to is a class type. Enumerate its constructors
2324 // to see if there is a suitable conversion.
2325 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002326
Douglas Gregor20093b42009-12-09 23:02:17 +00002327 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002328 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002329 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002330 NamedDecl *D = *Con;
2331 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2332
Douglas Gregor20093b42009-12-09 23:02:17 +00002333 // Find the constructor (which may be a template).
2334 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002335 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002336 if (ConstructorTmpl)
2337 Constructor = cast<CXXConstructorDecl>(
2338 ConstructorTmpl->getTemplatedDecl());
2339 else
John McCall9aa472c2010-03-19 07:35:19 +00002340 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002341
2342 if (!Constructor->isInvalidDecl() &&
2343 Constructor->isConvertingConstructor(AllowExplicit)) {
2344 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002345 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002346 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002347 &Initializer, 1, CandidateSet,
2348 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002349 else
John McCall9aa472c2010-03-19 07:35:19 +00002350 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002351 &Initializer, 1, CandidateSet,
2352 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002353 }
2354 }
2355 }
John McCall572fc622010-08-17 07:23:57 +00002356 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2357 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002358
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002359 const RecordType *T2RecordType = 0;
2360 if ((T2RecordType = T2->getAs<RecordType>()) &&
2361 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002362 // The type we're converting from is a class type, enumerate its conversion
2363 // functions.
2364 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2365
2366 // Determine the type we are converting to. If we are allowed to
2367 // convert to an rvalue, take the type that the destination type
2368 // refers to.
2369 QualType ToType = AllowRValues? cv1T1 : DestType;
2370
John McCalleec51cf2010-01-20 00:46:10 +00002371 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002372 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002373 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2374 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002375 NamedDecl *D = *I;
2376 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2377 if (isa<UsingShadowDecl>(D))
2378 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2379
2380 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2381 CXXConversionDecl *Conv;
2382 if (ConvTemplate)
2383 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2384 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002385 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002386
2387 // If the conversion function doesn't return a reference type,
2388 // it can't be considered for this conversion unless we're allowed to
2389 // consider rvalues.
2390 // FIXME: Do we need to make sure that we only consider conversion
2391 // candidates with reference-compatible results? That might be needed to
2392 // break recursion.
2393 if ((AllowExplicit || !Conv->isExplicit()) &&
2394 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2395 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002396 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002397 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 ToType, CandidateSet);
2399 else
John McCall9aa472c2010-03-19 07:35:19 +00002400 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002401 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002402 }
2403 }
2404 }
John McCall572fc622010-08-17 07:23:57 +00002405 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2406 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002407
2408 SourceLocation DeclLoc = Initializer->getLocStart();
2409
2410 // Perform overload resolution. If it fails, return the failed result.
2411 OverloadCandidateSet::iterator Best;
2412 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002413 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002414 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002415
Douglas Gregor20093b42009-12-09 23:02:17 +00002416 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002417
2418 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 if (isa<CXXConversionDecl>(Function))
2420 T2 = Function->getResultType();
2421 else
2422 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002423
2424 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002425 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002426 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002427
2428 // Determine whether we need to perform derived-to-base or
2429 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002430 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002431 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002432 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002433 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002434 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002435
Douglas Gregor20093b42009-12-09 23:02:17 +00002436 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002437 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002438 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregor63982352010-07-13 18:40:04 +00002439 = S.CompareReferenceRelationship(DeclLoc, T1,
2440 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002441 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002442 if (NewRefRelationship == Sema::Ref_Incompatible) {
2443 // If the type we've converted to is not reference-related to the
2444 // type we're looking for, then there is another conversion step
2445 // we need to perform to produce a temporary of the right type
2446 // that we'll be binding to.
2447 ImplicitConversionSequence ICS;
2448 ICS.setStandard();
2449 ICS.Standard = Best->FinalConversion;
2450 T2 = ICS.Standard.getToType(2);
2451 Sequence.AddConversionSequenceStep(ICS, T2);
2452 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002453 Sequence.AddDerivedToBaseCastStep(
2454 S.Context.getQualifiedType(T1,
2455 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002456 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002457 else if (NewObjCConversion)
2458 Sequence.AddObjCObjectConversionStep(
2459 S.Context.getQualifiedType(T1,
2460 T2.getNonReferenceType().getQualifiers()));
2461
Douglas Gregor20093b42009-12-09 23:02:17 +00002462 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002463 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00002464
2465 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2466 return OR_Success;
2467}
2468
Sebastian Redl4680bf22010-06-30 18:13:39 +00002469/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002470static void TryReferenceInitialization(Sema &S,
2471 const InitializedEntity &Entity,
2472 const InitializationKind &Kind,
2473 Expr *Initializer,
2474 InitializationSequence &Sequence) {
2475 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002476
Douglas Gregord6542d82009-12-22 15:35:07 +00002477 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002478 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002479 Qualifiers T1Quals;
2480 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002481 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002482 Qualifiers T2Quals;
2483 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002484 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002485
Douglas Gregor20093b42009-12-09 23:02:17 +00002486 // If the initializer is the address of an overloaded function, try
2487 // to resolve the overloaded function. If all goes well, T2 is the
2488 // type of the resulting function.
2489 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002490 DeclAccessPair Found;
Douglas Gregor3afb9772010-11-08 15:20:28 +00002491 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2492 T1,
2493 false,
2494 Found)) {
2495 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2496 cv2T2 = Fn->getType();
2497 T2 = cv2T2.getUnqualifiedType();
2498 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002499 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2500 return;
2501 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002502 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002503
Douglas Gregor20093b42009-12-09 23:02:17 +00002504 // Compute some basic properties of the types and the initializer.
2505 bool isLValueRef = DestType->isLValueReferenceType();
2506 bool isRValueRef = !isLValueRef;
2507 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002508 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002509 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002510 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002511 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2512 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002513
Douglas Gregor20093b42009-12-09 23:02:17 +00002514 // C++0x [dcl.init.ref]p5:
2515 // A reference to type "cv1 T1" is initialized by an expression of type
2516 // "cv2 T2" as follows:
2517 //
2518 // - If the reference is an lvalue reference and the initializer
2519 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002520 // Note the analogous bullet points for rvlaue refs to functions. Because
2521 // there are no function rvalues in C++, rvalue refs to functions are treated
2522 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002523 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002524 bool T1Function = T1->isFunctionType();
2525 if (isLValueRef || T1Function) {
2526 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002527 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2528 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2529 // reference-compatible with "cv2 T2," or
2530 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002531 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002532 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002533 // can occur. However, we do pay attention to whether it is a bit-field
2534 // to decide whether we're actually binding to a temporary created from
2535 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 if (DerivedToBase)
2537 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002538 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002539 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002540 else if (ObjCConversion)
2541 Sequence.AddObjCObjectConversionStep(
2542 S.Context.getQualifiedType(T1, T2Quals));
2543
Chandler Carruth5535c382010-01-12 20:32:25 +00002544 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002545 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002546 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002547 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002548 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 return;
2550 }
2551
2552 // - has a class type (i.e., T2 is a class type), where T1 is not
2553 // reference-related to T2, and can be implicitly converted to an
2554 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2555 // with "cv3 T3" (this conversion is selected by enumerating the
2556 // applicable conversion functions (13.3.1.6) and choosing the best
2557 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002558 // If we have an rvalue ref to function type here, the rhs must be
2559 // an rvalue.
2560 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2561 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002562 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2563 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002564 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002565 Sequence);
2566 if (ConvOvlResult == OR_Success)
2567 return;
John McCall1d318332010-01-12 00:44:57 +00002568 if (ConvOvlResult != OR_No_Viable_Function) {
2569 Sequence.SetOverloadFailure(
2570 InitializationSequence::FK_ReferenceInitOverloadFailed,
2571 ConvOvlResult);
2572 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002573 }
2574 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002575
Douglas Gregor20093b42009-12-09 23:02:17 +00002576 // - Otherwise, the reference shall be an lvalue reference to a
2577 // non-volatile const type (i.e., cv1 shall be const), or the reference
2578 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002579 // be an rvalue or have a function type.
2580 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002581 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002582 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002583 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2584 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2585 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002586 Sequence.SetOverloadFailure(
2587 InitializationSequence::FK_ReferenceInitOverloadFailed,
2588 ConvOvlResult);
2589 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002590 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002591 ? (RefRelationship == Sema::Ref_Related
2592 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2593 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2594 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2595 else
2596 Sequence.SetFailed(
2597 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002598
Douglas Gregor20093b42009-12-09 23:02:17 +00002599 return;
2600 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002601
2602 // - [If T1 is not a function type], if T2 is a class type and
2603 if (!T1Function && T2->isRecordType()) {
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002604 bool isXValue = InitCategory.isXValue();
Douglas Gregor20093b42009-12-09 23:02:17 +00002605 // - the initializer expression is an rvalue and "cv1 T1" is
2606 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002607 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002608 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002609 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2610 // compiler the freedom to perform a copy here or bind to the
2611 // object, while C++0x requires that we bind directly to the
2612 // object. Hence, we always bind to the object without making an
2613 // extra copy. However, in C++03 requires that we check for the
2614 // presence of a suitable copy constructor:
2615 //
2616 // The constructor that would be used to make the copy shall
2617 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002618 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002619 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2620
Douglas Gregor20093b42009-12-09 23:02:17 +00002621 if (DerivedToBase)
2622 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002623 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002624 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002625 else if (ObjCConversion)
2626 Sequence.AddObjCObjectConversionStep(
2627 S.Context.getQualifiedType(T1, T2Quals));
2628
Chandler Carruth5535c382010-01-12 20:32:25 +00002629 if (T1Quals != T2Quals)
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002630 Sequence.AddQualificationConversionStep(cv1T1,
John McCall5baba9d2010-08-25 10:28:54 +00002631 isXValue ? VK_XValue : VK_RValue);
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002632 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00002633 return;
2634 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002635
Douglas Gregor20093b42009-12-09 23:02:17 +00002636 // - T1 is not reference-related to T2 and the initializer expression
2637 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2638 // conversion is selected by enumerating the applicable conversion
2639 // functions (13.3.1.6) and choosing the best one through overload
2640 // resolution (13.3)),
2641 if (RefRelationship == Sema::Ref_Incompatible) {
2642 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2643 Kind, Initializer,
2644 /*AllowRValues=*/true,
2645 Sequence);
2646 if (ConvOvlResult)
2647 Sequence.SetOverloadFailure(
2648 InitializationSequence::FK_ReferenceInitOverloadFailed,
2649 ConvOvlResult);
2650
2651 return;
2652 }
2653
2654 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2655 return;
2656 }
2657
2658 // - If the initializer expression is an rvalue, with T2 an array type,
2659 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2660 // is bound to the object represented by the rvalue (see 3.10).
2661 // FIXME: How can an array type be reference-compatible with anything?
2662 // Don't we mean the element types of T1 and T2?
2663
2664 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2665 // from the initializer expression using the rules for a non-reference
2666 // copy initialization (8.5). The reference is then bound to the
2667 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002668
Douglas Gregor20093b42009-12-09 23:02:17 +00002669 // Determine whether we are allowed to call explicit constructors or
2670 // explicit conversion operators.
2671 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002672
2673 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2674
2675 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2676 /*SuppressUserConversions*/ false,
2677 AllowExplicit,
2678 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002679 // FIXME: Use the conversion function set stored in ICS to turn
2680 // this into an overloading ambiguity diagnostic. However, we need
2681 // to keep that set as an OverloadCandidateSet rather than as some
2682 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002683 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2684 Sequence.SetOverloadFailure(
2685 InitializationSequence::FK_ReferenceInitOverloadFailed,
2686 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002687 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2688 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002689 else
2690 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002691 return;
2692 }
2693
2694 // [...] If T1 is reference-related to T2, cv1 must be the
2695 // same cv-qualification as, or greater cv-qualification
2696 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002697 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2698 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002699 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002700 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002701 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2702 return;
2703 }
2704
Douglas Gregor20093b42009-12-09 23:02:17 +00002705 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2706 return;
2707}
2708
2709/// \brief Attempt character array initialization from a string literal
2710/// (C++ [dcl.init.string], C99 6.7.8).
2711static void TryStringLiteralInitialization(Sema &S,
2712 const InitializedEntity &Entity,
2713 const InitializationKind &Kind,
2714 Expr *Initializer,
2715 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002716 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002717 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002718}
2719
Douglas Gregor20093b42009-12-09 23:02:17 +00002720/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2721/// enumerates the constructors of the initialized entity and performs overload
2722/// resolution to select the best.
2723static void TryConstructorInitialization(Sema &S,
2724 const InitializedEntity &Entity,
2725 const InitializationKind &Kind,
2726 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002727 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002729 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002730
2731 // Build the candidate set directly in the initialization sequence
2732 // structure, so that it will persist if we fail.
2733 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2734 CandidateSet.clear();
2735
2736 // Determine whether we are allowed to call explicit constructors or
2737 // explicit conversion operators.
2738 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2739 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002740 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002741
2742 // The type we're constructing needs to be complete.
2743 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002744 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002745 return;
2746 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002747
2748 // The type we're converting to is a class type. Enumerate its constructors
2749 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002750 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2751 assert(DestRecordType && "Constructor initialization requires record type");
2752 CXXRecordDecl *DestRecordDecl
2753 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2754
Douglas Gregor51c56d62009-12-14 20:49:26 +00002755 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002756 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002757 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002758 NamedDecl *D = *Con;
2759 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002760 bool SuppressUserConversions = false;
2761
Douglas Gregor51c56d62009-12-14 20:49:26 +00002762 // Find the constructor (which may be a template).
2763 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002764 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002765 if (ConstructorTmpl)
2766 Constructor = cast<CXXConstructorDecl>(
2767 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002768 else {
John McCall9aa472c2010-03-19 07:35:19 +00002769 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002770
2771 // If we're performing copy initialization using a copy constructor, we
2772 // suppress user-defined conversions on the arguments.
2773 // FIXME: Move constructors?
2774 if (Kind.getKind() == InitializationKind::IK_Copy &&
2775 Constructor->isCopyConstructor())
2776 SuppressUserConversions = true;
2777 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002778
2779 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002780 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002781 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002782 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002783 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002784 Args, NumArgs, CandidateSet,
2785 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002786 else
John McCall9aa472c2010-03-19 07:35:19 +00002787 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002788 Args, NumArgs, CandidateSet,
2789 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002790 }
2791 }
2792
2793 SourceLocation DeclLoc = Kind.getLocation();
2794
2795 // Perform overload resolution. If it fails, return the failed result.
2796 OverloadCandidateSet::iterator Best;
2797 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002798 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002799 Sequence.SetOverloadFailure(
2800 InitializationSequence::FK_ConstructorOverloadFailed,
2801 Result);
2802 return;
2803 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002804
2805 // C++0x [dcl.init]p6:
2806 // If a program calls for the default initialization of an object
2807 // of a const-qualified type T, T shall be a class type with a
2808 // user-provided default constructor.
2809 if (Kind.getKind() == InitializationKind::IK_Default &&
2810 Entity.getType().isConstQualified() &&
2811 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2812 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2813 return;
2814 }
2815
Douglas Gregor51c56d62009-12-14 20:49:26 +00002816 // Add the constructor initialization step. Any cv-qualification conversion is
2817 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002818 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002819 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002820 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002821 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002822}
2823
Douglas Gregor71d17402009-12-15 00:01:57 +00002824/// \brief Attempt value initialization (C++ [dcl.init]p7).
2825static void TryValueInitialization(Sema &S,
2826 const InitializedEntity &Entity,
2827 const InitializationKind &Kind,
2828 InitializationSequence &Sequence) {
2829 // C++ [dcl.init]p5:
2830 //
2831 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002832 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002833
2834 // -- if T is an array type, then each element is value-initialized;
2835 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2836 T = AT->getElementType();
2837
2838 if (const RecordType *RT = T->getAs<RecordType>()) {
2839 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2840 // -- if T is a class type (clause 9) with a user-declared
2841 // constructor (12.1), then the default constructor for T is
2842 // called (and the initialization is ill-formed if T has no
2843 // accessible default constructor);
2844 //
2845 // FIXME: we really want to refer to a single subobject of the array,
2846 // but Entity doesn't have a way to capture that (yet).
2847 if (ClassDecl->hasUserDeclaredConstructor())
2848 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2849
Douglas Gregor16006c92009-12-16 18:50:27 +00002850 // -- if T is a (possibly cv-qualified) non-union class type
2851 // without a user-provided constructor, then the object is
2852 // zero-initialized and, if T’s implicitly-declared default
2853 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002854 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002855 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002856 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002857 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2858 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002859 }
2860 }
2861
Douglas Gregord6542d82009-12-22 15:35:07 +00002862 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002863 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2864}
2865
Douglas Gregor99a2e602009-12-16 01:38:02 +00002866/// \brief Attempt default initialization (C++ [dcl.init]p6).
2867static void TryDefaultInitialization(Sema &S,
2868 const InitializedEntity &Entity,
2869 const InitializationKind &Kind,
2870 InitializationSequence &Sequence) {
2871 assert(Kind.getKind() == InitializationKind::IK_Default);
2872
2873 // C++ [dcl.init]p6:
2874 // To default-initialize an object of type T means:
2875 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002876 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002877 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2878 DestType = Array->getElementType();
2879
2880 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2881 // constructor for T is called (and the initialization is ill-formed if
2882 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002883 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002884 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2885 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002886 }
2887
2888 // - otherwise, no initialization is performed.
2889 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2890
2891 // If a program calls for the default initialization of an object of
2892 // a const-qualified type T, T shall be a class type with a user-provided
2893 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002894 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002895 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2896}
2897
Douglas Gregor20093b42009-12-09 23:02:17 +00002898/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2899/// which enumerates all conversion functions and performs overload resolution
2900/// to select the best.
2901static void TryUserDefinedConversion(Sema &S,
2902 const InitializedEntity &Entity,
2903 const InitializationKind &Kind,
2904 Expr *Initializer,
2905 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002906 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2907
Douglas Gregord6542d82009-12-22 15:35:07 +00002908 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002909 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2910 QualType SourceType = Initializer->getType();
2911 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2912 "Must have a class type to perform a user-defined conversion");
2913
2914 // Build the candidate set directly in the initialization sequence
2915 // structure, so that it will persist if we fail.
2916 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2917 CandidateSet.clear();
2918
2919 // Determine whether we are allowed to call explicit constructors or
2920 // explicit conversion operators.
2921 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2922
2923 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2924 // The type we're converting to is a class type. Enumerate its constructors
2925 // to see if there is a suitable conversion.
2926 CXXRecordDecl *DestRecordDecl
2927 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2928
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002929 // Try to complete the type we're converting to.
2930 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002931 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002932 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002933 Con != ConEnd; ++Con) {
2934 NamedDecl *D = *Con;
2935 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002936
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002937 // Find the constructor (which may be a template).
2938 CXXConstructorDecl *Constructor = 0;
2939 FunctionTemplateDecl *ConstructorTmpl
2940 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002941 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002942 Constructor = cast<CXXConstructorDecl>(
2943 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002944 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002945 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002946
2947 if (!Constructor->isInvalidDecl() &&
2948 Constructor->isConvertingConstructor(AllowExplicit)) {
2949 if (ConstructorTmpl)
2950 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2951 /*ExplicitArgs*/ 0,
2952 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002953 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002954 else
2955 S.AddOverloadCandidate(Constructor, FoundDecl,
2956 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002957 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002958 }
2959 }
2960 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002961 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002962
2963 SourceLocation DeclLoc = Initializer->getLocStart();
2964
Douglas Gregor4a520a22009-12-14 17:27:33 +00002965 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2966 // The type we're converting from is a class type, enumerate its conversion
2967 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002968
Eli Friedman33c2da92009-12-20 22:12:03 +00002969 // We can only enumerate the conversion functions for a complete type; if
2970 // the type isn't complete, simply skip this step.
2971 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2972 CXXRecordDecl *SourceRecordDecl
2973 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002974
John McCalleec51cf2010-01-20 00:46:10 +00002975 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002976 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002977 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002978 E = Conversions->end();
2979 I != E; ++I) {
2980 NamedDecl *D = *I;
2981 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2982 if (isa<UsingShadowDecl>(D))
2983 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2984
2985 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2986 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002987 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002988 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002989 else
John McCall32daa422010-03-31 01:36:47 +00002990 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002991
2992 if (AllowExplicit || !Conv->isExplicit()) {
2993 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002994 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002995 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002996 CandidateSet);
2997 else
John McCall9aa472c2010-03-19 07:35:19 +00002998 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002999 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003000 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003001 }
3002 }
3003 }
3004
Douglas Gregor4a520a22009-12-14 17:27:33 +00003005 // Perform overload resolution. If it fails, return the failed result.
3006 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003007 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003008 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003009 Sequence.SetOverloadFailure(
3010 InitializationSequence::FK_UserConversionOverloadFailed,
3011 Result);
3012 return;
3013 }
John McCall1d318332010-01-12 00:44:57 +00003014
Douglas Gregor4a520a22009-12-14 17:27:33 +00003015 FunctionDecl *Function = Best->Function;
3016
3017 if (isa<CXXConstructorDecl>(Function)) {
3018 // Add the user-defined conversion step. Any cv-qualification conversion is
3019 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003020 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003021 return;
3022 }
3023
3024 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003025 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003026 if (ConvType->getAs<RecordType>()) {
3027 // If we're converting to a class type, there may be an copy if
3028 // the resulting temporary object (possible to create an object of
3029 // a base class type). That copy is not a separate conversion, so
3030 // we just make a note of the actual destination type (possibly a
3031 // base class of the type returned by the conversion function) and
3032 // let the user-defined conversion step handle the conversion.
3033 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3034 return;
3035 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003036
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003037 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3038
3039 // If the conversion following the call to the conversion function
3040 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003041 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3042 Best->FinalConversion.Third) {
3043 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003044 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003045 ICS.Standard = Best->FinalConversion;
3046 Sequence.AddConversionSequenceStep(ICS, DestType);
3047 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003048}
3049
Douglas Gregor20093b42009-12-09 23:02:17 +00003050InitializationSequence::InitializationSequence(Sema &S,
3051 const InitializedEntity &Entity,
3052 const InitializationKind &Kind,
3053 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003054 unsigned NumArgs)
3055 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003056 ASTContext &Context = S.Context;
3057
3058 // C++0x [dcl.init]p16:
3059 // The semantics of initializers are as follows. The destination type is
3060 // the type of the object or reference being initialized and the source
3061 // type is the type of the initializer expression. The source type is not
3062 // defined when the initializer is a braced-init-list or when it is a
3063 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003064 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003065
3066 if (DestType->isDependentType() ||
3067 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3068 SequenceKind = DependentSequence;
3069 return;
3070 }
3071
John McCall241d5582010-12-07 22:54:16 +00003072 for (unsigned I = 0; I != NumArgs; ++I)
3073 if (Args[I]->getObjectKind() == OK_ObjCProperty)
3074 S.ConvertPropertyForRValue(Args[I]);
3075
Douglas Gregor20093b42009-12-09 23:02:17 +00003076 QualType SourceType;
3077 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003078 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003079 Initializer = Args[0];
3080 if (!isa<InitListExpr>(Initializer))
3081 SourceType = Initializer->getType();
3082 }
3083
3084 // - If the initializer is a braced-init-list, the object is
3085 // list-initialized (8.5.4).
3086 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3087 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003088 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003089 }
3090
3091 // - If the destination type is a reference type, see 8.5.3.
3092 if (DestType->isReferenceType()) {
3093 // C++0x [dcl.init.ref]p1:
3094 // A variable declared to be a T& or T&&, that is, "reference to type T"
3095 // (8.3.2), shall be initialized by an object, or function, of type T or
3096 // by an object that can be converted into a T.
3097 // (Therefore, multiple arguments are not permitted.)
3098 if (NumArgs != 1)
3099 SetFailed(FK_TooManyInitsForReference);
3100 else
3101 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3102 return;
3103 }
3104
3105 // - If the destination type is an array of characters, an array of
3106 // char16_t, an array of char32_t, or an array of wchar_t, and the
3107 // initializer is a string literal, see 8.5.2.
3108 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3109 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3110 return;
3111 }
3112
3113 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003114 if (Kind.getKind() == InitializationKind::IK_Value ||
3115 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003116 TryValueInitialization(S, Entity, Kind, *this);
3117 return;
3118 }
3119
Douglas Gregor99a2e602009-12-16 01:38:02 +00003120 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003121 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003122 TryDefaultInitialization(S, Entity, Kind, *this);
3123 return;
3124 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003125
Douglas Gregor20093b42009-12-09 23:02:17 +00003126 // - Otherwise, if the destination type is an array, the program is
3127 // ill-formed.
3128 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3129 if (AT->getElementType()->isAnyCharacterType())
3130 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3131 else
3132 SetFailed(FK_ArrayNeedsInitList);
3133
3134 return;
3135 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003136
3137 // Handle initialization in C
3138 if (!S.getLangOptions().CPlusPlus) {
3139 setSequenceKind(CAssignment);
3140 AddCAssignmentStep(DestType);
3141 return;
3142 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003143
3144 // - If the destination type is a (possibly cv-qualified) class type:
3145 if (DestType->isRecordType()) {
3146 // - If the initialization is direct-initialization, or if it is
3147 // copy-initialization where the cv-unqualified version of the
3148 // source type is the same class as, or a derived class of, the
3149 // class of the destination, constructors are considered. [...]
3150 if (Kind.getKind() == InitializationKind::IK_Direct ||
3151 (Kind.getKind() == InitializationKind::IK_Copy &&
3152 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3153 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003154 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003155 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003156 // - Otherwise (i.e., for the remaining copy-initialization cases),
3157 // user-defined conversion sequences that can convert from the source
3158 // type to the destination type or (when a conversion function is
3159 // used) to a derived class thereof are enumerated as described in
3160 // 13.3.1.4, and the best one is chosen through overload resolution
3161 // (13.3).
3162 else
3163 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3164 return;
3165 }
3166
Douglas Gregor99a2e602009-12-16 01:38:02 +00003167 if (NumArgs > 1) {
3168 SetFailed(FK_TooManyInitsForScalar);
3169 return;
3170 }
3171 assert(NumArgs == 1 && "Zero-argument case handled above");
3172
Douglas Gregor20093b42009-12-09 23:02:17 +00003173 // - Otherwise, if the source type is a (possibly cv-qualified) class
3174 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003175 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003176 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3177 return;
3178 }
3179
3180 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003181 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003182 // conversions (Clause 4) will be used, if necessary, to convert the
3183 // initializer expression to the cv-unqualified version of the
3184 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003185 if (S.TryImplicitConversion(*this, Entity, Initializer,
3186 /*SuppressUserConversions*/ true,
3187 /*AllowExplicitConversions*/ false,
3188 /*InOverloadResolution*/ false))
Douglas Gregor8e960432010-11-08 03:40:48 +00003189 {
John McCall241d5582010-12-07 22:54:16 +00003190 if (Initializer->getType() == Context.OverloadTy)
Douglas Gregor8e960432010-11-08 03:40:48 +00003191 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3192 else
3193 SetFailed(InitializationSequence::FK_ConversionFailed);
3194 }
John McCall369371c2010-06-04 02:29:22 +00003195 else
3196 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003197}
3198
3199InitializationSequence::~InitializationSequence() {
3200 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3201 StepEnd = Steps.end();
3202 Step != StepEnd; ++Step)
3203 Step->Destroy();
3204}
3205
3206//===----------------------------------------------------------------------===//
3207// Perform initialization
3208//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003209static Sema::AssignmentAction
3210getAssignmentAction(const InitializedEntity &Entity) {
3211 switch(Entity.getKind()) {
3212 case InitializedEntity::EK_Variable:
3213 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003214 case InitializedEntity::EK_Exception:
3215 case InitializedEntity::EK_Base:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003216 return Sema::AA_Initializing;
3217
3218 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003219 if (Entity.getDecl() &&
3220 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3221 return Sema::AA_Sending;
3222
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003223 return Sema::AA_Passing;
3224
3225 case InitializedEntity::EK_Result:
3226 return Sema::AA_Returning;
3227
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003228 case InitializedEntity::EK_Temporary:
3229 // FIXME: Can we tell apart casting vs. converting?
3230 return Sema::AA_Casting;
3231
3232 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003233 case InitializedEntity::EK_ArrayElement:
3234 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003235 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003236 return Sema::AA_Initializing;
3237 }
3238
3239 return Sema::AA_Converting;
3240}
3241
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003242/// \brief Whether we should binding a created object as a temporary when
3243/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003244static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003245 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003246 case InitializedEntity::EK_ArrayElement:
3247 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003248 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003249 case InitializedEntity::EK_New:
3250 case InitializedEntity::EK_Variable:
3251 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003252 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003253 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003254 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003255 return false;
3256
3257 case InitializedEntity::EK_Parameter:
3258 case InitializedEntity::EK_Temporary:
3259 return true;
3260 }
3261
3262 llvm_unreachable("missed an InitializedEntity kind?");
3263}
3264
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003265/// \brief Whether the given entity, when initialized with an object
3266/// created for that initialization, requires destruction.
3267static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3268 switch (Entity.getKind()) {
3269 case InitializedEntity::EK_Member:
3270 case InitializedEntity::EK_Result:
3271 case InitializedEntity::EK_New:
3272 case InitializedEntity::EK_Base:
3273 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003274 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003275 return false;
3276
3277 case InitializedEntity::EK_Variable:
3278 case InitializedEntity::EK_Parameter:
3279 case InitializedEntity::EK_Temporary:
3280 case InitializedEntity::EK_ArrayElement:
3281 case InitializedEntity::EK_Exception:
3282 return true;
3283 }
3284
3285 llvm_unreachable("missed an InitializedEntity kind?");
3286}
3287
Douglas Gregor523d46a2010-04-18 07:40:54 +00003288/// \brief Make a (potentially elidable) temporary copy of the object
3289/// provided by the given initializer by calling the appropriate copy
3290/// constructor.
3291///
3292/// \param S The Sema object used for type-checking.
3293///
3294/// \param T The type of the temporary object, which must either by
3295/// the type of the initializer expression or a superclass thereof.
3296///
3297/// \param Enter The entity being initialized.
3298///
3299/// \param CurInit The initializer expression.
3300///
3301/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3302/// is permitted in C++03 (but not C++0x) when binding a reference to
3303/// an rvalue.
3304///
3305/// \returns An expression that copies the initializer expression into
3306/// a temporary object, or an error expression if a copy could not be
3307/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003308static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003309 QualType T,
3310 const InitializedEntity &Entity,
3311 ExprResult CurInit,
3312 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003313 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003314 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003315 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003316 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003317 Class = cast<CXXRecordDecl>(Record->getDecl());
3318 if (!Class)
3319 return move(CurInit);
3320
3321 // C++0x [class.copy]p34:
3322 // When certain criteria are met, an implementation is allowed to
3323 // omit the copy/move construction of a class object, even if the
3324 // copy/move constructor and/or destructor for the object have
3325 // side effects. [...]
3326 // - when a temporary class object that has not been bound to a
3327 // reference (12.2) would be copied/moved to a class object
3328 // with the same cv-unqualified type, the copy/move operation
3329 // can be omitted by constructing the temporary object
3330 // directly into the target of the omitted copy/move
3331 //
3332 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003333 // elision for return statements and throw expressions are handled as part
3334 // of constructor initialization, while copy elision for exception handlers
3335 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003336 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003337 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338 switch (Entity.getKind()) {
3339 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003340 Loc = Entity.getReturnLoc();
3341 break;
3342
3343 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003344 Loc = Entity.getThrowLoc();
3345 break;
3346
3347 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003348 Loc = Entity.getDecl()->getLocation();
3349 break;
3350
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003351 case InitializedEntity::EK_ArrayElement:
3352 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003353 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003354 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003355 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003356 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003357 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003358 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003359 Loc = CurInitExpr->getLocStart();
3360 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003361 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003362
3363 // Make sure that the type we are copying is complete.
3364 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3365 return move(CurInit);
3366
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003367 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003368 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003369 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003370 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003371 Con != ConEnd; ++Con) {
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003372 // Only consider copy constructors and constructor templates. Per
3373 // C++0x [dcl.init]p16, second bullet to class types, this
3374 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003375 CXXConstructorDecl *Constructor = 0;
3376
3377 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
3378 // Handle copy constructors, only.
3379 if (!Constructor || Constructor->isInvalidDecl() ||
3380 !Constructor->isCopyConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003381 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003382 continue;
3383
3384 DeclAccessPair FoundDecl
3385 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3386 S.AddOverloadCandidate(Constructor, FoundDecl,
3387 &CurInitExpr, 1, CandidateSet);
3388 continue;
3389 }
3390
3391 // Handle constructor templates.
3392 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3393 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003394 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003395
Douglas Gregor6493cc52010-11-08 17:16:59 +00003396 Constructor = cast<CXXConstructorDecl>(
3397 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003398 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003399 continue;
3400
3401 // FIXME: Do we need to limit this to copy-constructor-like
3402 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003403 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003404 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3405 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3406 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003407 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003408
3409 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00003410 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003411 case OR_Success:
3412 break;
3413
3414 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003415 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3416 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3417 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003418 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003419 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003420 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003421 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003422 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003423 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003424
3425 case OR_Ambiguous:
3426 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003427 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003428 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003429 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003430 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003431
3432 case OR_Deleted:
3433 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003434 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003435 << CurInitExpr->getSourceRange();
3436 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3437 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003438 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003439 }
3440
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003441 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003442 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003443 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003444
Anders Carlsson9a68a672010-04-21 18:47:17 +00003445 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003446 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003447
3448 if (IsExtraneousCopy) {
3449 // If this is a totally extraneous copy for C++03 reference
3450 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003451 // expression. We don't generate an (elided) copy operation here
3452 // because doing so would require us to pass down a flag to avoid
3453 // infinite recursion, where each step adds another extraneous,
3454 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003455
Douglas Gregor2559a702010-04-18 07:57:34 +00003456 // Instantiate the default arguments of any extra parameters in
3457 // the selected copy constructor, as if we were going to create a
3458 // proper call to the copy constructor.
3459 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3460 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3461 if (S.RequireCompleteType(Loc, Parm->getType(),
3462 S.PDiag(diag::err_call_incomplete_argument)))
3463 break;
3464
3465 // Build the default argument expression; we don't actually care
3466 // if this succeeds or not, because this routine will complain
3467 // if there was a problem.
3468 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3469 }
3470
Douglas Gregor523d46a2010-04-18 07:40:54 +00003471 return S.Owned(CurInitExpr);
3472 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003473
3474 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003475 // constructor call (we might have derived-to-base conversions, or
3476 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003477 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003478 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003479 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003480
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003481 // Actually perform the constructor call.
3482 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003483 move_arg(ConstructorArgs),
3484 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003485 CXXConstructExpr::CK_Complete,
3486 SourceRange());
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003487
3488 // If we're supposed to bind temporaries, do so.
3489 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3490 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3491 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003492}
Douglas Gregor20093b42009-12-09 23:02:17 +00003493
Douglas Gregora41a8c52010-04-22 00:20:18 +00003494void InitializationSequence::PrintInitLocationNote(Sema &S,
3495 const InitializedEntity &Entity) {
3496 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3497 if (Entity.getDecl()->getLocation().isInvalid())
3498 return;
3499
3500 if (Entity.getDecl()->getDeclName())
3501 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3502 << Entity.getDecl()->getDeclName();
3503 else
3504 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3505 }
3506}
3507
John McCall60d7b3a2010-08-24 06:29:42 +00003508ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003509InitializationSequence::Perform(Sema &S,
3510 const InitializedEntity &Entity,
3511 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003512 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003513 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003514 if (SequenceKind == FailedSequence) {
3515 unsigned NumArgs = Args.size();
3516 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003517 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003518 }
3519
3520 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003521 // If the declaration is a non-dependent, incomplete array type
3522 // that has an initializer, then its type will be completed once
3523 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003524 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003525 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003526 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003527 if (const IncompleteArrayType *ArrayT
3528 = S.Context.getAsIncompleteArrayType(DeclType)) {
3529 // FIXME: We don't currently have the ability to accurately
3530 // compute the length of an initializer list without
3531 // performing full type-checking of the initializer list
3532 // (since we have to determine where braces are implicitly
3533 // introduced and such). So, we fall back to making the array
3534 // type a dependently-sized array type with no specified
3535 // bound.
3536 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3537 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003538
Douglas Gregord87b61f2009-12-10 17:56:55 +00003539 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003540 if (DeclaratorDecl *DD = Entity.getDecl()) {
3541 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3542 TypeLoc TL = TInfo->getTypeLoc();
3543 if (IncompleteArrayTypeLoc *ArrayLoc
3544 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3545 Brackets = ArrayLoc->getBracketsRange();
3546 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003547 }
3548
3549 *ResultType
3550 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3551 /*NumElts=*/0,
3552 ArrayT->getSizeModifier(),
3553 ArrayT->getIndexTypeCVRQualifiers(),
3554 Brackets);
3555 }
3556
3557 }
3558 }
3559
Eli Friedman08544622009-12-22 02:35:53 +00003560 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003561 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003562
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003563 if (Args.size() == 0)
3564 return S.Owned((Expr *)0);
3565
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 unsigned NumArgs = Args.size();
3567 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3568 SourceLocation(),
3569 (Expr **)Args.release(),
3570 NumArgs,
3571 SourceLocation()));
3572 }
3573
Douglas Gregor99a2e602009-12-16 01:38:02 +00003574 if (SequenceKind == NoInitialization)
3575 return S.Owned((Expr *)0);
3576
Douglas Gregord6542d82009-12-22 15:35:07 +00003577 QualType DestType = Entity.getType().getNonReferenceType();
3578 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003579 // the same as Entity.getDecl()->getType() in cases involving type merging,
3580 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003581 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003582 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003583 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003584
John McCall60d7b3a2010-08-24 06:29:42 +00003585 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003586
3587 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3588
3589 // For initialization steps that start with a single initializer,
3590 // grab the only argument out the Args and place it into the "current"
3591 // initializer.
3592 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003593 case SK_ResolveAddressOfOverloadedFunction:
3594 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003595 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003596 case SK_CastDerivedToBaseLValue:
3597 case SK_BindReference:
3598 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003599 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003600 case SK_UserConversion:
3601 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003602 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003603 case SK_QualificationConversionRValue:
3604 case SK_ConversionSequence:
3605 case SK_ListInitialization:
3606 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003607 case SK_StringInit:
John McCallf6a16482010-12-04 03:47:34 +00003608 case SK_ObjCObjectConversion: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003609 assert(Args.size() == 1);
John McCallf6a16482010-12-04 03:47:34 +00003610 Expr *CurInitExpr = Args.get()[0];
3611 if (!CurInitExpr) return ExprError();
3612
3613 // Read from a property when initializing something with it.
3614 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3615 S.ConvertPropertyForRValue(CurInitExpr);
3616
3617 CurInit = ExprResult(CurInitExpr);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003618 break;
John McCallf6a16482010-12-04 03:47:34 +00003619 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003620
3621 case SK_ConstructorInitialization:
3622 case SK_ZeroInitialization:
3623 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 }
3625
3626 // Walk through the computed steps for the initialization sequence,
3627 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003628 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003629 for (step_iterator Step = step_begin(), StepEnd = step_end();
3630 Step != StepEnd; ++Step) {
3631 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003632 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003633
John McCallf6a16482010-12-04 03:47:34 +00003634 Expr *CurInitExpr = CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003635 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003636
3637 switch (Step->Kind) {
3638 case SK_ResolveAddressOfOverloadedFunction:
3639 // Overload resolution determined which function invoke; update the
3640 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003641 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003642 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003643 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003644 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003645 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003646 break;
3647
3648 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003649 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003650 case SK_CastDerivedToBaseLValue: {
3651 // We have a derived-to-base cast that produces either an rvalue or an
3652 // lvalue. Perform that cast.
3653
John McCallf871d0c2010-08-07 06:22:56 +00003654 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003655
Douglas Gregor20093b42009-12-09 23:02:17 +00003656 // Casts to inaccessible base classes are allowed with C-style casts.
3657 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3658 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3659 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003660 CurInitExpr->getSourceRange(),
3661 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003662 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003663
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003664 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3665 QualType T = SourceType;
3666 if (const PointerType *Pointer = T->getAs<PointerType>())
3667 T = Pointer->getPointeeType();
3668 if (const RecordType *RecordTy = T->getAs<RecordType>())
3669 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3670 cast<CXXRecordDecl>(RecordTy->getDecl()));
3671 }
3672
John McCall5baba9d2010-08-25 10:28:54 +00003673 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003674 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003675 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003676 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003677 VK_XValue :
3678 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003679 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3680 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003681 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003682 CurInit.get(),
3683 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003684 break;
3685 }
3686
3687 case SK_BindReference:
3688 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3689 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3690 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003691 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003692 << BitField->getDeclName()
3693 << CurInitExpr->getSourceRange();
3694 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003695 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003696 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003697
Anders Carlsson09380262010-01-31 17:18:49 +00003698 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003699 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003700 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3701 << Entity.getType().isVolatileQualified()
3702 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003703 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003704 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003705 }
3706
Douglas Gregor20093b42009-12-09 23:02:17 +00003707 // Reference binding does not have any corresponding ASTs.
3708
3709 // Check exception specifications
3710 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003711 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003712
Douglas Gregor20093b42009-12-09 23:02:17 +00003713 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003714
Douglas Gregor20093b42009-12-09 23:02:17 +00003715 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003716 // Reference binding does not have any corresponding ASTs.
3717
Douglas Gregor20093b42009-12-09 23:02:17 +00003718 // Check exception specifications
3719 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003720 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003721
Douglas Gregor20093b42009-12-09 23:02:17 +00003722 break;
3723
Douglas Gregor523d46a2010-04-18 07:40:54 +00003724 case SK_ExtraneousCopyToTemporary:
3725 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3726 /*IsExtraneousCopy=*/true);
3727 break;
3728
Douglas Gregor20093b42009-12-09 23:02:17 +00003729 case SK_UserConversion: {
3730 // We have a user-defined conversion that invokes either a constructor
3731 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003732 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003733 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003734 FunctionDecl *Fn = Step->Function.Function;
3735 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003736 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003737 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003739 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003740 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003741 SourceLocation Loc = CurInitExpr->getLocStart();
3742 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003743
Douglas Gregor20093b42009-12-09 23:02:17 +00003744 // Determine the arguments required to actually perform the constructor
3745 // call.
3746 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003747 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003748 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003749 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003750
3751 // Build the an expression that constructs a temporary.
3752 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003753 move_arg(ConstructorArgs),
3754 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003755 CXXConstructExpr::CK_Complete,
3756 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003757 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003758 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003759
Anders Carlsson9a68a672010-04-21 18:47:17 +00003760 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003761 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003762 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003763
John McCall2de56d12010-08-25 11:45:40 +00003764 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003765 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3766 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3767 S.IsDerivedFrom(SourceType, Class))
3768 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003769
3770 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003771 } else {
3772 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003773 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003774 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003775 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003776 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003777 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003778
Douglas Gregor20093b42009-12-09 23:02:17 +00003779 // FIXME: Should we move this initialization into a separate
3780 // derived-to-base conversion? I believe the answer is "no", because
3781 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003782 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003783 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003784 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003785
3786 // Do a little dance to make sure that CurInit has the proper
3787 // pointer.
3788 CurInit.release();
3789
3790 // Build the actual call to the conversion function.
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003791 CurInit = S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003792 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003793 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003794
John McCall2de56d12010-08-25 11:45:40 +00003795 CastKind = CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003796
3797 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003798 }
3799
Douglas Gregor2f599792010-04-02 18:24:57 +00003800 bool RequiresCopy = !IsCopy &&
3801 getKind() != InitializationSequence::ReferenceBinding;
3802 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003803 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003804 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3805 CurInitExpr = static_cast<Expr *>(CurInit.get());
3806 QualType T = CurInitExpr->getType();
3807 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003808 CXXDestructorDecl *Destructor
3809 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003810 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3811 S.PDiag(diag::err_access_dtor_temp) << T);
3812 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003813 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003814 }
3815 }
3816
Douglas Gregor20093b42009-12-09 23:02:17 +00003817 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003818 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003819 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3820 CurInitExpr->getType(),
3821 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003822 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003823
Douglas Gregor2f599792010-04-02 18:24:57 +00003824 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003825 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3826 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003827
Douglas Gregor20093b42009-12-09 23:02:17 +00003828 break;
3829 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003830
Douglas Gregor20093b42009-12-09 23:02:17 +00003831 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003832 case SK_QualificationConversionXValue:
3833 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003834 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003835 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003836 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003837 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003838 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003839 VK_XValue :
3840 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003841 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003842 CurInit.release();
3843 CurInit = S.Owned(CurInitExpr);
3844 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003845 }
3846
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003847 case SK_ConversionSequence: {
3848 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3849
3850 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregora3998bd2010-12-02 21:47:04 +00003851 getAssignmentAction(Entity),
3852 IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003853 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003854
3855 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003856 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003857 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003858 }
3859
Douglas Gregord87b61f2009-12-10 17:56:55 +00003860 case SK_ListInitialization: {
3861 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3862 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003863 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003864 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003865
3866 CurInit.release();
3867 CurInit = S.Owned(InitList);
3868 break;
3869 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003870
3871 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003872 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003873 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003874 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003875
Douglas Gregor51c56d62009-12-14 20:49:26 +00003876 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003877 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003878 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3879 ? Kind.getEqualLoc()
3880 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003881
3882 if (Kind.getKind() == InitializationKind::IK_Default) {
3883 // Force even a trivial, implicit default constructor to be
3884 // semantically checked. We do this explicitly because we don't build
3885 // the definition for completely trivial constructors.
3886 CXXRecordDecl *ClassDecl = Constructor->getParent();
3887 assert(ClassDecl && "No parent class for constructor.");
3888 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3889 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3890 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3891 }
3892
Douglas Gregor51c56d62009-12-14 20:49:26 +00003893 // Determine the arguments required to actually perform the constructor
3894 // call.
3895 if (S.CompleteConstructorCall(Constructor, move(Args),
3896 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003897 return ExprError();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003898
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003899
Douglas Gregor91be6f52010-03-02 17:18:33 +00003900 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003901 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003902 (Kind.getKind() == InitializationKind::IK_Direct ||
3903 Kind.getKind() == InitializationKind::IK_Value)) {
3904 // An explicitly-constructed temporary, e.g., X(1, 2).
3905 unsigned NumExprs = ConstructorArgs.size();
3906 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003907 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003908 S.DiagnoseUseOfDecl(Constructor, Loc);
3909
Douglas Gregorab6677e2010-09-08 00:15:04 +00003910 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3911 if (!TSInfo)
3912 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3913
Douglas Gregor91be6f52010-03-02 17:18:33 +00003914 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3915 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00003916 TSInfo,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003917 Exprs,
3918 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003919 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003920 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003921 } else {
3922 CXXConstructExpr::ConstructionKind ConstructKind =
3923 CXXConstructExpr::CK_Complete;
3924
3925 if (Entity.getKind() == InitializedEntity::EK_Base) {
3926 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3927 CXXConstructExpr::CK_VirtualBase :
3928 CXXConstructExpr::CK_NonVirtualBase;
3929 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003930
Chandler Carruth428edaf2010-10-25 08:47:36 +00003931 // Only get the parenthesis range if it is a direct construction.
3932 SourceRange parenRange =
3933 Kind.getKind() == InitializationKind::IK_Direct ?
3934 Kind.getParenRange() : SourceRange();
3935
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003936 // If the entity allows NRVO, mark the construction as elidable
3937 // unconditionally.
3938 if (Entity.allowsNRVO())
3939 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3940 Constructor, /*Elidable=*/true,
3941 move_arg(ConstructorArgs),
3942 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003943 ConstructKind,
3944 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003945 else
3946 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3947 Constructor,
3948 move_arg(ConstructorArgs),
3949 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003950 ConstructKind,
3951 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003952 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003953 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003954 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003955
3956 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003957 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003958 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003959 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003960
Douglas Gregor2f599792010-04-02 18:24:57 +00003961 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003962 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003963
Douglas Gregor51c56d62009-12-14 20:49:26 +00003964 break;
3965 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003966
3967 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003968 step_iterator NextStep = Step;
3969 ++NextStep;
3970 if (NextStep != StepEnd &&
3971 NextStep->Kind == SK_ConstructorInitialization) {
3972 // The need for zero-initialization is recorded directly into
3973 // the call to the object's constructor within the next step.
3974 ConstructorInitRequiresZeroInit = true;
3975 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3976 S.getLangOptions().CPlusPlus &&
3977 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00003978 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3979 if (!TSInfo)
3980 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3981 Kind.getRange().getBegin());
3982
3983 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3984 TSInfo->getType().getNonLValueExprType(S.Context),
3985 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00003986 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003987 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003988 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003989 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003990 break;
3991 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003992
3993 case SK_CAssignment: {
3994 QualType SourceType = CurInitExpr->getType();
3995 Sema::AssignConvertType ConvTy =
3996 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003997
3998 // If this is a call, allow conversion to a transparent union.
3999 if (ConvTy != Sema::Compatible &&
4000 Entity.getKind() == InitializedEntity::EK_Parameter &&
4001 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4002 == Sema::Compatible)
4003 ConvTy = Sema::Compatible;
4004
Douglas Gregora41a8c52010-04-22 00:20:18 +00004005 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004006 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4007 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00004008 CurInitExpr,
4009 getAssignmentAction(Entity),
4010 &Complained)) {
4011 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004012 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004013 } else if (Complained)
4014 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004015
4016 CurInit.release();
4017 CurInit = S.Owned(CurInitExpr);
4018 break;
4019 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004020
4021 case SK_StringInit: {
4022 QualType Ty = Step->Type;
4023 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4024 break;
4025 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004026
4027 case SK_ObjCObjectConversion:
4028 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004029 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00004030 S.CastCategory(CurInitExpr));
4031 CurInit.release();
4032 CurInit = S.Owned(CurInitExpr);
4033 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004034 }
4035 }
John McCall15d7d122010-11-11 03:21:53 +00004036
4037 // Diagnose non-fatal problems with the completed initialization.
4038 if (Entity.getKind() == InitializedEntity::EK_Member &&
4039 cast<FieldDecl>(Entity.getDecl())->isBitField())
4040 S.CheckBitFieldInitialization(Kind.getLocation(),
4041 cast<FieldDecl>(Entity.getDecl()),
4042 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00004043
4044 return move(CurInit);
4045}
4046
4047//===----------------------------------------------------------------------===//
4048// Diagnose initialization failures
4049//===----------------------------------------------------------------------===//
4050bool InitializationSequence::Diagnose(Sema &S,
4051 const InitializedEntity &Entity,
4052 const InitializationKind &Kind,
4053 Expr **Args, unsigned NumArgs) {
4054 if (SequenceKind != FailedSequence)
4055 return false;
4056
Douglas Gregord6542d82009-12-22 15:35:07 +00004057 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004058 switch (Failure) {
4059 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004060 // FIXME: Customize for the initialized entity?
4061 if (NumArgs == 0)
4062 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4063 << DestType.getNonReferenceType();
4064 else // FIXME: diagnostic below could be better!
4065 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4066 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004067 break;
4068
4069 case FK_ArrayNeedsInitList:
4070 case FK_ArrayNeedsInitListOrStringLiteral:
4071 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4072 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4073 break;
4074
John McCall6bb80172010-03-30 21:47:33 +00004075 case FK_AddressOfOverloadFailed: {
4076 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 S.ResolveAddressOfOverloadedFunction(Args[0],
4078 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004079 true,
4080 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004081 break;
John McCall6bb80172010-03-30 21:47:33 +00004082 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004083
4084 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004085 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004086 switch (FailedOverloadResult) {
4087 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004088 if (Failure == FK_UserConversionOverloadFailed)
4089 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4090 << Args[0]->getType() << DestType
4091 << Args[0]->getSourceRange();
4092 else
4093 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4094 << DestType << Args[0]->getType()
4095 << Args[0]->getSourceRange();
4096
John McCall120d63c2010-08-24 20:38:10 +00004097 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004098 break;
4099
4100 case OR_No_Viable_Function:
4101 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4102 << Args[0]->getType() << DestType.getNonReferenceType()
4103 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004104 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004105 break;
4106
4107 case OR_Deleted: {
4108 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4109 << Args[0]->getType() << DestType.getNonReferenceType()
4110 << Args[0]->getSourceRange();
4111 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004112 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004113 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4114 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004115 if (Ovl == OR_Deleted) {
4116 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4117 << Best->Function->isDeleted();
4118 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004119 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004120 }
4121 break;
4122 }
4123
4124 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004125 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004126 break;
4127 }
4128 break;
4129
4130 case FK_NonConstLValueReferenceBindingToTemporary:
4131 case FK_NonConstLValueReferenceBindingToUnrelated:
4132 S.Diag(Kind.getLocation(),
4133 Failure == FK_NonConstLValueReferenceBindingToTemporary
4134 ? diag::err_lvalue_reference_bind_to_temporary
4135 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004136 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004137 << DestType.getNonReferenceType()
4138 << Args[0]->getType()
4139 << Args[0]->getSourceRange();
4140 break;
4141
4142 case FK_RValueReferenceBindingToLValue:
4143 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4144 << Args[0]->getSourceRange();
4145 break;
4146
4147 case FK_ReferenceInitDropsQualifiers:
4148 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4149 << DestType.getNonReferenceType()
4150 << Args[0]->getType()
4151 << Args[0]->getSourceRange();
4152 break;
4153
4154 case FK_ReferenceInitFailed:
4155 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4156 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004157 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004158 << Args[0]->getType()
4159 << Args[0]->getSourceRange();
4160 break;
4161
4162 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004163 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4164 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004165 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004166 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004167 << Args[0]->getType()
4168 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004169 break;
4170
4171 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004172 SourceRange R;
4173
4174 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004175 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004176 InitList->getLocEnd());
Douglas Gregor19311e72010-09-08 21:40:08 +00004177 else
4178 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004179
Douglas Gregor19311e72010-09-08 21:40:08 +00004180 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4181 if (Kind.isCStyleOrFunctionalCast())
4182 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4183 << R;
4184 else
4185 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4186 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004187 break;
4188 }
4189
4190 case FK_ReferenceBindingToInitList:
4191 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4192 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4193 break;
4194
4195 case FK_InitListBadDestinationType:
4196 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4197 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4198 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004199
4200 case FK_ConstructorOverloadFailed: {
4201 SourceRange ArgsRange;
4202 if (NumArgs)
4203 ArgsRange = SourceRange(Args[0]->getLocStart(),
4204 Args[NumArgs - 1]->getLocEnd());
4205
4206 // FIXME: Using "DestType" for the entity we're printing is probably
4207 // bad.
4208 switch (FailedOverloadResult) {
4209 case OR_Ambiguous:
4210 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4211 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004212 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4213 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004214 break;
4215
4216 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004217 if (Kind.getKind() == InitializationKind::IK_Default &&
4218 (Entity.getKind() == InitializedEntity::EK_Base ||
4219 Entity.getKind() == InitializedEntity::EK_Member) &&
4220 isa<CXXConstructorDecl>(S.CurContext)) {
4221 // This is implicit default initialization of a member or
4222 // base within a constructor. If no viable function was
4223 // found, notify the user that she needs to explicitly
4224 // initialize this base/member.
4225 CXXConstructorDecl *Constructor
4226 = cast<CXXConstructorDecl>(S.CurContext);
4227 if (Entity.getKind() == InitializedEntity::EK_Base) {
4228 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4229 << Constructor->isImplicit()
4230 << S.Context.getTypeDeclType(Constructor->getParent())
4231 << /*base=*/0
4232 << Entity.getType();
4233
4234 RecordDecl *BaseDecl
4235 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4236 ->getDecl();
4237 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4238 << S.Context.getTagDeclType(BaseDecl);
4239 } else {
4240 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4241 << Constructor->isImplicit()
4242 << S.Context.getTypeDeclType(Constructor->getParent())
4243 << /*member=*/1
4244 << Entity.getName();
4245 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4246
4247 if (const RecordType *Record
4248 = Entity.getType()->getAs<RecordType>())
4249 S.Diag(Record->getDecl()->getLocation(),
4250 diag::note_previous_decl)
4251 << S.Context.getTagDeclType(Record->getDecl());
4252 }
4253 break;
4254 }
4255
Douglas Gregor51c56d62009-12-14 20:49:26 +00004256 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4257 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004258 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004259 break;
4260
4261 case OR_Deleted: {
4262 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4263 << true << DestType << ArgsRange;
4264 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004265 OverloadingResult Ovl
4266 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004267 if (Ovl == OR_Deleted) {
4268 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4269 << Best->Function->isDeleted();
4270 } else {
4271 llvm_unreachable("Inconsistent overload resolution?");
4272 }
4273 break;
4274 }
4275
4276 case OR_Success:
4277 llvm_unreachable("Conversion did not fail!");
4278 break;
4279 }
4280 break;
4281 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004282
4283 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004284 if (Entity.getKind() == InitializedEntity::EK_Member &&
4285 isa<CXXConstructorDecl>(S.CurContext)) {
4286 // This is implicit default-initialization of a const member in
4287 // a constructor. Complain that it needs to be explicitly
4288 // initialized.
4289 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4290 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4291 << Constructor->isImplicit()
4292 << S.Context.getTypeDeclType(Constructor->getParent())
4293 << /*const=*/1
4294 << Entity.getName();
4295 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4296 << Entity.getName();
4297 } else {
4298 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4299 << DestType << (bool)DestType->getAs<RecordType>();
4300 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004301 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004302
4303 case FK_Incomplete:
4304 S.RequireCompleteType(Kind.getLocation(), DestType,
4305 diag::err_init_incomplete_type);
4306 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004307 }
4308
Douglas Gregora41a8c52010-04-22 00:20:18 +00004309 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004310 return true;
4311}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004312
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004313void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4314 switch (SequenceKind) {
4315 case FailedSequence: {
4316 OS << "Failed sequence: ";
4317 switch (Failure) {
4318 case FK_TooManyInitsForReference:
4319 OS << "too many initializers for reference";
4320 break;
4321
4322 case FK_ArrayNeedsInitList:
4323 OS << "array requires initializer list";
4324 break;
4325
4326 case FK_ArrayNeedsInitListOrStringLiteral:
4327 OS << "array requires initializer list or string literal";
4328 break;
4329
4330 case FK_AddressOfOverloadFailed:
4331 OS << "address of overloaded function failed";
4332 break;
4333
4334 case FK_ReferenceInitOverloadFailed:
4335 OS << "overload resolution for reference initialization failed";
4336 break;
4337
4338 case FK_NonConstLValueReferenceBindingToTemporary:
4339 OS << "non-const lvalue reference bound to temporary";
4340 break;
4341
4342 case FK_NonConstLValueReferenceBindingToUnrelated:
4343 OS << "non-const lvalue reference bound to unrelated type";
4344 break;
4345
4346 case FK_RValueReferenceBindingToLValue:
4347 OS << "rvalue reference bound to an lvalue";
4348 break;
4349
4350 case FK_ReferenceInitDropsQualifiers:
4351 OS << "reference initialization drops qualifiers";
4352 break;
4353
4354 case FK_ReferenceInitFailed:
4355 OS << "reference initialization failed";
4356 break;
4357
4358 case FK_ConversionFailed:
4359 OS << "conversion failed";
4360 break;
4361
4362 case FK_TooManyInitsForScalar:
4363 OS << "too many initializers for scalar";
4364 break;
4365
4366 case FK_ReferenceBindingToInitList:
4367 OS << "referencing binding to initializer list";
4368 break;
4369
4370 case FK_InitListBadDestinationType:
4371 OS << "initializer list for non-aggregate, non-scalar type";
4372 break;
4373
4374 case FK_UserConversionOverloadFailed:
4375 OS << "overloading failed for user-defined conversion";
4376 break;
4377
4378 case FK_ConstructorOverloadFailed:
4379 OS << "constructor overloading failed";
4380 break;
4381
4382 case FK_DefaultInitOfConst:
4383 OS << "default initialization of a const variable";
4384 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004385
4386 case FK_Incomplete:
4387 OS << "initialization of incomplete type";
4388 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004389 }
4390 OS << '\n';
4391 return;
4392 }
4393
4394 case DependentSequence:
4395 OS << "Dependent sequence: ";
4396 return;
4397
4398 case UserDefinedConversion:
4399 OS << "User-defined conversion sequence: ";
4400 break;
4401
4402 case ConstructorInitialization:
4403 OS << "Constructor initialization sequence: ";
4404 break;
4405
4406 case ReferenceBinding:
4407 OS << "Reference binding: ";
4408 break;
4409
4410 case ListInitialization:
4411 OS << "List initialization: ";
4412 break;
4413
4414 case ZeroInitialization:
4415 OS << "Zero initialization\n";
4416 return;
4417
4418 case NoInitialization:
4419 OS << "No initialization\n";
4420 return;
4421
4422 case StandardConversion:
4423 OS << "Standard conversion: ";
4424 break;
4425
4426 case CAssignment:
4427 OS << "C assignment: ";
4428 break;
4429
4430 case StringInit:
4431 OS << "String initialization: ";
4432 break;
4433 }
4434
4435 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4436 if (S != step_begin()) {
4437 OS << " -> ";
4438 }
4439
4440 switch (S->Kind) {
4441 case SK_ResolveAddressOfOverloadedFunction:
4442 OS << "resolve address of overloaded function";
4443 break;
4444
4445 case SK_CastDerivedToBaseRValue:
4446 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4447 break;
4448
Sebastian Redl906082e2010-07-20 04:20:21 +00004449 case SK_CastDerivedToBaseXValue:
4450 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4451 break;
4452
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004453 case SK_CastDerivedToBaseLValue:
4454 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4455 break;
4456
4457 case SK_BindReference:
4458 OS << "bind reference to lvalue";
4459 break;
4460
4461 case SK_BindReferenceToTemporary:
4462 OS << "bind reference to a temporary";
4463 break;
4464
Douglas Gregor523d46a2010-04-18 07:40:54 +00004465 case SK_ExtraneousCopyToTemporary:
4466 OS << "extraneous C++03 copy to temporary";
4467 break;
4468
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004469 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004470 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004471 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004472
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004473 case SK_QualificationConversionRValue:
4474 OS << "qualification conversion (rvalue)";
4475
Sebastian Redl906082e2010-07-20 04:20:21 +00004476 case SK_QualificationConversionXValue:
4477 OS << "qualification conversion (xvalue)";
4478
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004479 case SK_QualificationConversionLValue:
4480 OS << "qualification conversion (lvalue)";
4481 break;
4482
4483 case SK_ConversionSequence:
4484 OS << "implicit conversion sequence (";
4485 S->ICS->DebugPrint(); // FIXME: use OS
4486 OS << ")";
4487 break;
4488
4489 case SK_ListInitialization:
4490 OS << "list initialization";
4491 break;
4492
4493 case SK_ConstructorInitialization:
4494 OS << "constructor initialization";
4495 break;
4496
4497 case SK_ZeroInitialization:
4498 OS << "zero initialization";
4499 break;
4500
4501 case SK_CAssignment:
4502 OS << "C assignment";
4503 break;
4504
4505 case SK_StringInit:
4506 OS << "string initialization";
4507 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004508
4509 case SK_ObjCObjectConversion:
4510 OS << "Objective-C object conversion";
4511 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004512 }
4513 }
4514}
4515
4516void InitializationSequence::dump() const {
4517 dump(llvm::errs());
4518}
4519
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004520//===----------------------------------------------------------------------===//
4521// Initialization helper functions
4522//===----------------------------------------------------------------------===//
John McCall60d7b3a2010-08-24 06:29:42 +00004523ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004524Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4525 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004526 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004527 if (Init.isInvalid())
4528 return ExprError();
4529
John McCall15d7d122010-11-11 03:21:53 +00004530 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004531 assert(InitE && "No initialization expression?");
4532
4533 if (EqualLoc.isInvalid())
4534 EqualLoc = InitE->getLocStart();
4535
4536 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4537 EqualLoc);
4538 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4539 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004540 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004541}