blob: e410f2f9a0d7fca40b6032b7f1e023f8700b7de8 [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//
Rafael Espindola12ce0a02011-07-14 22:58:04 +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.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000013//
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"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000180 unsigned &StructuredIndex,
181 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000199 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000200 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000201 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckReferenceType(const InitializedEntity &Entity,
205 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000206 unsigned &Index,
207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000210 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000213 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000214 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000215 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000216 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000218 unsigned &StructuredIndex,
219 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000220 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000221 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000222 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000223 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000224 InitListExpr *StructuredList,
225 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000227 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000228 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000229 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000230 RecordDecl::field_iterator *NextField,
231 llvm::APSInt *NextElementIndex,
232 unsigned &Index,
233 InitListExpr *StructuredList,
234 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000235 bool FinishSubobjectInit,
236 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000237 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
238 QualType CurrentObjectType,
239 InitListExpr *StructuredList,
240 unsigned StructuredIndex,
241 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000242 void UpdateStructuredListElement(InitListExpr *StructuredList,
243 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000244 Expr *expr);
245 int numArrayElements(QualType DeclType);
246 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000247
Douglas Gregord6d37de2009-12-22 00:05:34 +0000248 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
249 const InitializedEntity &ParentEntity,
250 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000251 void FillInValueInitializations(const InitializedEntity &Entity,
252 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000253public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000254 InitListChecker(Sema &S, const InitializedEntity &Entity,
255 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000256 bool HadError() { return hadError; }
257
258 // @brief Retrieves the fully-structured initializer list used for
259 // semantic analysis and code generation.
260 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
261};
Chris Lattner8b419b92009-02-24 22:48:58 +0000262} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000263
Douglas Gregord6d37de2009-12-22 00:05:34 +0000264void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
265 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000266 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000267 bool &RequiresSecondPass) {
268 SourceLocation Loc = ILE->getSourceRange().getBegin();
269 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000271 = InitializedEntity::InitializeMember(Field, &ParentEntity);
272 if (Init >= NumInits || !ILE->getInit(Init)) {
273 // FIXME: We probably don't need to handle references
274 // specially here, since value-initialization of references is
275 // handled in InitializationSequence.
276 if (Field->getType()->isReferenceType()) {
277 // C++ [dcl.init.aggr]p9:
278 // If an incomplete or empty initializer-list leaves a
279 // member of reference type uninitialized, the program is
280 // ill-formed.
281 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
282 << Field->getType()
283 << ILE->getSyntacticForm()->getSourceRange();
284 SemaRef.Diag(Field->getLocation(),
285 diag::note_uninit_reference_member);
286 hadError = true;
287 return;
288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
291 true);
292 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
293 if (!InitSeq) {
294 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
295 hadError = true;
296 return;
297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000298
John McCall60d7b3a2010-08-24 06:29:42 +0000299 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000300 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000301 if (MemberInit.isInvalid()) {
302 hadError = true;
303 return;
304 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000305
Douglas Gregord6d37de2009-12-22 00:05:34 +0000306 if (hadError) {
307 // Do nothing
308 } else if (Init < NumInits) {
309 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000310 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000311 // Value-initialization requires a constructor call, so
312 // extend the initializer list to include the constructor
313 // call and make a note that we'll need to take another pass
314 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000315 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000316 RequiresSecondPass = true;
317 }
318 } else if (InitListExpr *InnerILE
319 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000320 FillInValueInitializations(MemberEntity, InnerILE,
321 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322}
323
Douglas Gregor4c678342009-01-28 21:54:33 +0000324/// Recursively replaces NULL values within the given initializer list
325/// with expressions that perform value-initialization of the
326/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
329 InitListExpr *ILE,
330 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000331 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000332 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000333 SourceLocation Loc = ILE->getSourceRange().getBegin();
334 if (ILE->getSyntacticForm())
335 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremenek6217b802009-07-29 21:53:49 +0000337 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000338 if (RType->getDecl()->isUnion() &&
339 ILE->getInitializedFieldInUnion())
340 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
341 Entity, ILE, RequiresSecondPass);
342 else {
343 unsigned Init = 0;
344 for (RecordDecl::field_iterator
345 Field = RType->getDecl()->field_begin(),
346 FieldEnd = RType->getDecl()->field_end();
347 Field != FieldEnd; ++Field) {
348 if (Field->isUnnamedBitfield())
349 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000350
Douglas Gregord6d37de2009-12-22 00:05:34 +0000351 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000352 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000353
354 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
355 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357
Douglas Gregord6d37de2009-12-22 00:05:34 +0000358 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000359
Douglas Gregord6d37de2009-12-22 00:05:34 +0000360 // Only look at the first initialization of a union.
361 if (RType->getDecl()->isUnion())
362 break;
363 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000364 }
365
366 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000367 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000368
369 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000371 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 unsigned NumInits = ILE->getNumInits();
373 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000374 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000375 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
377 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000378 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000379 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000380 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000384 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000386 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000387
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000388
Douglas Gregor87fd7032009-02-02 17:43:21 +0000389 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000390 if (hadError)
391 return;
392
Anders Carlssond3d824d2010-01-23 04:34:47 +0000393 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
394 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 ElementEntity.setElementIndex(Init);
396
Douglas Gregor87fd7032009-02-02 17:43:21 +0000397 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
399 true);
400 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
401 if (!InitSeq) {
402 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 hadError = true;
404 return;
405 }
406
John McCall60d7b3a2010-08-24 06:29:42 +0000407 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000408 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000409 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000410 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000411 return;
412 }
413
414 if (hadError) {
415 // Do nothing
416 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000417 // For arrays, just set the expression used for value-initialization
418 // of the "holes" in the array.
419 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
420 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
421 else
422 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000423 } else {
424 // For arrays, just set the expression used for value-initialization
425 // of the rest of elements and exit.
426 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
427 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
428 return;
429 }
430
Sebastian Redl7491c492011-06-05 13:59:11 +0000431 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000432 // Value-initialization requires a constructor call, so
433 // extend the initializer list to include the constructor
434 // call and make a note that we'll need to take another pass
435 // through the initializer list.
436 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
437 RequiresSecondPass = true;
438 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000439 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000440 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
442 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000443 }
444}
445
Chris Lattner68355a52009-01-29 05:10:57 +0000446
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
448 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000449 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000450 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000451
Eli Friedmanb85f7072008-05-19 19:16:24 +0000452 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000454 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000455 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000456 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000457 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000458 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000459
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000460 if (!hadError) {
461 bool RequiresSecondPass = false;
462 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000463 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000464 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000465 RequiresSecondPass);
466 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000467}
468
469int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000470 // FIXME: use a proper constant
471 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000472 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000473 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000474 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
475 }
476 return maxElements;
477}
478
479int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000480 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000482 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000483 Field = structDecl->field_begin(),
484 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 Field != FieldEnd; ++Field) {
486 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
487 ++InitializableMembers;
488 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000489 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000490 return std::min(InitializableMembers, 1);
491 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000492}
493
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000494void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000495 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000496 QualType T, unsigned &Index,
497 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000498 unsigned &StructuredIndex,
499 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Steve Naroff0cca7492008-05-01 22:18:59 +0000502 if (T->isArrayType())
503 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000504 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000505 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000506 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000507 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000508 else
509 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000510
Eli Friedman402256f2008-05-25 13:49:22 +0000511 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000512 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000513 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000515 hadError = true;
516 return;
517 }
518
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 // Build a structured initializer list corresponding to this subobject.
520 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000521 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
522 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000523 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
524 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000525 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000526
Douglas Gregor4c678342009-01-28 21:54:33 +0000527 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000528 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000529 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000530 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000531 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000532 StructuredSubobjectInitIndex,
533 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000534 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000535 StructuredSubobjectInitList->setType(T);
536
Douglas Gregored8a93d2009-03-01 17:12:46 +0000537 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000538 // range corresponds with the end of the last initializer it used.
539 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000541 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
542 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000545 // Warn about missing braces.
546 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000547 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
548 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000549 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000551 "{")
552 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000554 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000555 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000556}
557
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000558void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000559 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000560 unsigned &Index,
561 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000562 unsigned &StructuredIndex,
563 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000565 SyntacticToSemantic[IList] = StructuredList;
566 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000569 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
570 IList->setType(ExprTy);
571 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000572 if (hadError)
573 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000574
Eli Friedman638e1442008-05-25 13:22:35 +0000575 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000576 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000577 if (StructuredIndex == 1 &&
578 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000579 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000580 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000581 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000582 hadError = true;
583 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000584 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000586 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000587 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000588 // Don't complain for incomplete types, since we'll get an error
589 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000590 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000591 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000592 CurrentObjectType->isArrayType()? 0 :
593 CurrentObjectType->isVectorType()? 1 :
594 CurrentObjectType->isScalarType()? 2 :
595 CurrentObjectType->isUnionType()? 3 :
596 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000597
598 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (SemaRef.getLangOptions().CPlusPlus) {
600 DK = diag::err_excess_initializers;
601 hadError = true;
602 }
Nate Begeman08634522009-07-07 21:53:06 +0000603 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
604 DK = diag::err_excess_initializers;
605 hadError = true;
606 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000607
Chris Lattner08202542009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000609 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000610 }
611 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000612
Eli Friedman759f2522009-05-16 11:45:48 +0000613 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000614 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000615 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000616 << FixItHint::CreateRemoval(IList->getLocStart())
617 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000618}
619
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000620void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000621 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000622 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000623 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000626 unsigned &StructuredIndex,
627 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000628 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 CheckScalarType(Entity, IList, DeclType, Index,
630 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000631 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000633 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000634 } else if (DeclType->isAggregateType()) {
635 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000636 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000637 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 StructuredList, StructuredIndex,
640 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000641 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000642 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000643 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000644 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000646 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000650 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
651 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000652 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000653 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000654 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000655 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 } else if (DeclType->isRecordType()) {
657 // C++ [dcl.init]p14:
658 // [...] If the class is an aggregate (8.5.1), and the initializer
659 // is a brace-enclosed list, see 8.5.1.
660 //
661 // Note: 8.5.1 is handled below; here, we diagnose the case where
662 // we have an initializer list and a destination type that is not
663 // an aggregate.
664 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 << DeclType << IList->getSourceRange();
667 hadError = true;
668 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000669 CheckReferenceType(Entity, IList, DeclType, Index,
670 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000671 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000672 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
673 << DeclType;
674 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000675 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000676 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
677 << DeclType;
678 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000679 }
680}
681
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000682void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000683 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 unsigned &Index,
686 InitListExpr *StructuredList,
687 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000688 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000689 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
690 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000692 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000693 = getStructuredSubobjectInit(IList, Index, ElemType,
694 StructuredList, StructuredIndex,
695 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000696 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000697 newStructuredList, newStructuredIndex);
698 ++StructuredIndex;
699 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000700 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000701 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000702 return CheckScalarType(Entity, IList, ElemType, Index,
703 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000704 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000705 return CheckReferenceType(Entity, IList, ElemType, Index,
706 StructuredList, StructuredIndex);
707 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000708
John McCallfef8b342011-02-21 07:57:55 +0000709 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
710 // arrayType can be incomplete if we're initializing a flexible
711 // array member. There's nothing we can do with the completed
712 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713
John McCallfef8b342011-02-21 07:57:55 +0000714 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
715 CheckStringInit(Str, ElemType, arrayType, SemaRef);
716 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000717 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000718 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000719 }
John McCallfef8b342011-02-21 07:57:55 +0000720
721 // Fall through for subaggregate initialization.
722
723 } else if (SemaRef.getLangOptions().CPlusPlus) {
724 // C++ [dcl.init.aggr]p12:
725 // All implicit type conversions (clause 4) are considered when
Rafael Espindola12ce0a02011-07-14 22:58:04 +0000726 // initializing the aggregate member with an ini- tializer from
John McCallfef8b342011-02-21 07:57:55 +0000727 // an initializer-list. If the initializer can initialize a
728 // member, the member is initialized. [...]
729
730 // FIXME: Better EqualLoc?
731 InitializationKind Kind =
732 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
733 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
734
735 if (Seq) {
736 ExprResult Result =
737 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
738 if (Result.isInvalid())
739 hadError = true;
740
741 UpdateStructuredListElement(StructuredList, StructuredIndex,
742 Result.takeAs<Expr>());
743 ++Index;
744 return;
745 }
746
747 // Fall through for subaggregate initialization
748 } else {
749 // C99 6.7.8p13:
750 //
751 // The initializer for a structure or union object that has
752 // automatic storage duration shall be either an initializer
753 // list as described below, or a single expression that has
754 // compatible structure or union type. In the latter case, the
755 // initial value of the object, including unnamed members, is
756 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000757 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000758 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000759 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000760 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000761 if (ExprRes.isInvalid())
762 hadError = true;
763 else {
764 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
765 if (ExprRes.isInvalid())
766 hadError = true;
767 }
768 UpdateStructuredListElement(StructuredList, StructuredIndex,
769 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000770 ++Index;
771 return;
772 }
John Wiegley429bb272011-04-08 18:41:53 +0000773 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000774 // Fall through for subaggregate initialization
775 }
776
777 // C++ [dcl.init.aggr]p12:
778 //
779 // [...] Otherwise, if the member is itself a non-empty
780 // subaggregate, brace elision is assumed and the initializer is
781 // considered for the initialization of the first member of
782 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000783 if (!SemaRef.getLangOptions().OpenCL &&
784 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000785 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
786 StructuredIndex);
787 ++StructuredIndex;
788 } else {
789 // We cannot initialize this element, so let
790 // PerformCopyInitialization produce the appropriate diagnostic.
791 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000792 SemaRef.Owned(expr),
793 /*TopLevelOfInitList=*/true);
John McCallfef8b342011-02-21 07:57:55 +0000794 hadError = true;
795 ++Index;
796 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000798}
799
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000800void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000801 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000802 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000803 InitListExpr *StructuredList,
804 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000805 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000806 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000807 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000808 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000809 ++Index;
810 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000811 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000812 }
John McCallb934c2d2010-11-11 00:46:36 +0000813
814 Expr *expr = IList->getInit(Index);
815 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
816 SemaRef.Diag(SubIList->getLocStart(),
817 diag::warn_many_braces_around_scalar_init)
818 << SubIList->getSourceRange();
819
820 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
821 StructuredIndex);
822 return;
823 } else if (isa<DesignatedInitExpr>(expr)) {
824 SemaRef.Diag(expr->getSourceRange().getBegin(),
825 diag::err_designator_for_scalar_init)
826 << DeclType << expr->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832
833 ExprResult Result =
834 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000835 SemaRef.Owned(expr),
836 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000837
838 Expr *ResultExpr = 0;
839
840 if (Result.isInvalid())
841 hadError = true; // types weren't compatible.
842 else {
843 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000844
John McCallb934c2d2010-11-11 00:46:36 +0000845 if (ResultExpr != expr) {
846 // The type was promoted, update initializer list.
847 IList->setInit(Index, ResultExpr);
848 }
849 }
850 if (hadError)
851 ++StructuredIndex;
852 else
853 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
854 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000855}
856
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000857void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
858 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000859 unsigned &Index,
860 InitListExpr *StructuredList,
861 unsigned &StructuredIndex) {
862 if (Index < IList->getNumInits()) {
863 Expr *expr = IList->getInit(Index);
864 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000866 << DeclType << IList->getSourceRange();
867 hadError = true;
868 ++Index;
869 ++StructuredIndex;
870 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000871 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000872
John McCall60d7b3a2010-08-24 06:29:42 +0000873 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000874 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000875 SemaRef.Owned(expr),
876 /*TopLevelOfInitList=*/true);
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000877
878 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000879 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000880
881 expr = Result.takeAs<Expr>();
882 IList->setInit(Index, expr);
883
Douglas Gregor930d8b52009-01-30 22:09:00 +0000884 if (hadError)
885 ++StructuredIndex;
886 else
887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
888 ++Index;
889 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000890 // FIXME: It would be wonderful if we could point at the actual member. In
891 // general, it would be useful to pass location information down the stack,
892 // so that we know the location (or decl) of the "current object" being
893 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000894 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000895 diag::err_init_reference_member_uninitialized)
896 << DeclType
897 << IList->getSourceRange();
898 hadError = true;
899 ++Index;
900 ++StructuredIndex;
901 return;
902 }
903}
904
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000905void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000906 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000907 unsigned &Index,
908 InitListExpr *StructuredList,
909 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000910 if (Index >= IList->getNumInits())
911 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000912
John McCall20e047a2010-10-30 00:11:39 +0000913 const VectorType *VT = DeclType->getAs<VectorType>();
914 unsigned maxElements = VT->getNumElements();
915 unsigned numEltsInit = 0;
916 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000917
John McCall20e047a2010-10-30 00:11:39 +0000918 if (!SemaRef.getLangOptions().OpenCL) {
919 // If the initializing element is a vector, try to copy-initialize
920 // instead of breaking it apart (which is doomed to failure anyway).
921 Expr *Init = IList->getInit(Index);
922 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
923 ExprResult Result =
924 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000925 SemaRef.Owned(Init),
926 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +0000927
928 Expr *ResultExpr = 0;
929 if (Result.isInvalid())
930 hadError = true; // types weren't compatible.
931 else {
932 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
John McCall20e047a2010-10-30 00:11:39 +0000934 if (ResultExpr != Init) {
935 // The type was promoted, update initializer list.
936 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000937 }
938 }
John McCall20e047a2010-10-30 00:11:39 +0000939 if (hadError)
940 ++StructuredIndex;
941 else
942 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
943 ++Index;
944 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
John McCall20e047a2010-10-30 00:11:39 +0000947 InitializedEntity ElementEntity =
948 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
John McCall20e047a2010-10-30 00:11:39 +0000950 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
951 // Don't attempt to go past the end of the init list
952 if (Index >= IList->getNumInits())
953 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954
John McCall20e047a2010-10-30 00:11:39 +0000955 ElementEntity.setElementIndex(Index);
956 CheckSubElementType(ElementEntity, IList, elementType, Index,
957 StructuredList, StructuredIndex);
958 }
959 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000960 }
John McCall20e047a2010-10-30 00:11:39 +0000961
962 InitializedEntity ElementEntity =
963 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000964
John McCall20e047a2010-10-30 00:11:39 +0000965 // OpenCL initializers allows vectors to be constructed from vectors.
966 for (unsigned i = 0; i < maxElements; ++i) {
967 // Don't attempt to go past the end of the init list
968 if (Index >= IList->getNumInits())
969 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000970
John McCall20e047a2010-10-30 00:11:39 +0000971 ElementEntity.setElementIndex(Index);
972
973 QualType IType = IList->getInit(Index)->getType();
974 if (!IType->isVectorType()) {
975 CheckSubElementType(ElementEntity, IList, elementType, Index,
976 StructuredList, StructuredIndex);
977 ++numEltsInit;
978 } else {
979 QualType VecType;
980 const VectorType *IVT = IType->getAs<VectorType>();
981 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
John McCall20e047a2010-10-30 00:11:39 +0000983 if (IType->isExtVectorType())
984 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
985 else
986 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000987 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000988 CheckSubElementType(ElementEntity, IList, VecType, Index,
989 StructuredList, StructuredIndex);
990 numEltsInit += numIElts;
991 }
992 }
993
994 // OpenCL requires all elements to be initialized.
995 if (numEltsInit != maxElements)
996 if (SemaRef.getLangOptions().OpenCL)
997 SemaRef.Diag(IList->getSourceRange().getBegin(),
998 diag::err_vector_incorrect_num_initializers)
999 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000}
1001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001002void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001003 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001004 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001005 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001006 unsigned &Index,
1007 InitListExpr *StructuredList,
1008 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001009 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1010
Steve Naroff0cca7492008-05-01 22:18:59 +00001011 // Check for the special-case of initializing an array with a string.
1012 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001013 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001014 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001015 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001016 // We place the string literal directly into the resulting
1017 // initializer list. This is the only place where the structure
1018 // of the structured initializer list doesn't match exactly,
1019 // because doing so would involve allocating one character
1020 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001021 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001022 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001023 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001024 return;
1025 }
1026 }
John McCallce6c9b72011-02-21 07:22:22 +00001027 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001028 // Check for VLAs; in standard C it would be possible to check this
1029 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1030 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001031 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001032 diag::err_variable_object_no_init)
1033 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001034 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001035 ++Index;
1036 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001037 return;
1038 }
1039
Douglas Gregor05c13a32009-01-22 00:58:24 +00001040 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001041 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1042 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001043 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001044 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001045 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001046 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001047 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001048 maxElementsKnown = true;
1049 }
1050
John McCallce6c9b72011-02-21 07:22:22 +00001051 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 while (Index < IList->getNumInits()) {
1053 Expr *Init = IList->getInit(Index);
1054 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001055 // If we're not the subobject that matches up with the '{' for
1056 // the designator, we shouldn't be handling the
1057 // designator. Return immediately.
1058 if (!SubobjectIsDesignatorContext)
1059 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001060
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061 // Handle this designated initializer. elementIndex will be
1062 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001063 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001064 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001065 StructuredList, StructuredIndex, true,
1066 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 hadError = true;
1068 continue;
1069 }
1070
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001071 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001072 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001073 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001074 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001075 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001076
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001077 // If the array is of incomplete type, keep track of the number of
1078 // elements in the initializer.
1079 if (!maxElementsKnown && elementIndex > maxElements)
1080 maxElements = elementIndex;
1081
Douglas Gregor05c13a32009-01-22 00:58:24 +00001082 continue;
1083 }
1084
1085 // If we know the maximum number of elements, and we've already
1086 // hit it, stop consuming elements in the initializer list.
1087 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001089
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001090 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001092 Entity);
1093 // Check this element.
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 ++elementIndex;
1097
1098 // If the array is of incomplete type, keep track of the number of
1099 // elements in the initializer.
1100 if (!maxElementsKnown && elementIndex > maxElements)
1101 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001102 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001103 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001104 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001105 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001106 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001107 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001108 // Sizing an array implicitly to zero is not allowed by ISO C,
1109 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001110 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001111 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001113
Mike Stump1eb44332009-09-09 15:08:12 +00001114 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001115 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001116 }
1117}
1118
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001119void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001120 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001121 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001122 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001123 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001124 unsigned &Index,
1125 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001126 unsigned &StructuredIndex,
1127 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001128 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Eli Friedmanb85f7072008-05-19 19:16:24 +00001130 // If the record is invalid, some of it's members are invalid. To avoid
1131 // confusion, we forgo checking the intializer for the entire record.
1132 if (structDecl->isInvalidDecl()) {
1133 hadError = true;
1134 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001135 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001136
1137 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1138 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001139 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001140 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001141 Field != FieldEnd; ++Field) {
1142 if (Field->getDeclName()) {
1143 StructuredList->setInitializedFieldInUnion(*Field);
1144 break;
1145 }
1146 }
1147 return;
1148 }
1149
Douglas Gregor05c13a32009-01-22 00:58:24 +00001150 // If structDecl is a forward declaration, this loop won't do
1151 // anything except look at designated initializers; That's okay,
1152 // because an error should get printed out elsewhere. It might be
1153 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001154 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001155 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001156 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001157 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001158 while (Index < IList->getNumInits()) {
1159 Expr *Init = IList->getInit(Index);
1160
1161 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001162 // If we're not the subobject that matches up with the '{' for
1163 // the designator, we shouldn't be handling the
1164 // designator. Return immediately.
1165 if (!SubobjectIsDesignatorContext)
1166 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001167
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001168 // Handle this designated initializer. Field will be updated to
1169 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001170 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001171 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001172 StructuredList, StructuredIndex,
1173 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 hadError = true;
1175
Douglas Gregordfb5e592009-02-12 19:00:39 +00001176 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001177
1178 // Disable check for missing fields when designators are used.
1179 // This matches gcc behaviour.
1180 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001181 continue;
1182 }
1183
1184 if (Field == FieldEnd) {
1185 // We've run out of fields. We're done.
1186 break;
1187 }
1188
Douglas Gregordfb5e592009-02-12 19:00:39 +00001189 // We've already initialized a member of a union. We're done.
1190 if (InitializedSomething && DeclType->isUnionType())
1191 break;
1192
Douglas Gregor44b43212008-12-11 16:49:14 +00001193 // If we've hit the flexible array member at the end, we're done.
1194 if (Field->getType()->isIncompleteArrayType())
1195 break;
1196
Douglas Gregor0bb76892009-01-29 16:53:55 +00001197 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001198 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001200 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001201 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001202
Douglas Gregor54001c12011-06-29 21:51:31 +00001203 // Make sure we can use this declaration.
1204 if (SemaRef.DiagnoseUseOfDecl(*Field,
1205 IList->getInit(Index)->getLocStart())) {
1206 ++Index;
1207 ++Field;
1208 hadError = true;
1209 continue;
1210 }
1211
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001212 InitializedEntity MemberEntity =
1213 InitializedEntity::InitializeMember(*Field, &Entity);
1214 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1215 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001216 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001217
1218 if (DeclType->isUnionType()) {
1219 // Initialize the first field within the union.
1220 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001221 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001222
1223 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001224 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001225
John McCall80639de2010-03-11 19:32:38 +00001226 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001227 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001228 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1229 // It is possible we have one or more unnamed bitfields remaining.
1230 // Find first (if any) named field and emit warning.
1231 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1232 it != end; ++it) {
1233 if (!it->isUnnamedBitfield()) {
1234 SemaRef.Diag(IList->getSourceRange().getEnd(),
1235 diag::warn_missing_field_initializers) << it->getName();
1236 break;
1237 }
1238 }
1239 }
1240
Mike Stump1eb44332009-09-09 15:08:12 +00001241 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001242 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001243 return;
1244
1245 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001246 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001247 (!isa<InitListExpr>(IList->getInit(Index)) ||
1248 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001249 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001250 diag::err_flexible_array_init_nonempty)
1251 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001252 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001253 << *Field;
1254 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001255 ++Index;
1256 return;
1257 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001258 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001259 diag::ext_flexible_array_init)
1260 << IList->getInit(Index)->getSourceRange().getBegin();
1261 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1262 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001263 }
1264
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001265 InitializedEntity MemberEntity =
1266 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001268 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001269 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001270 StructuredList, StructuredIndex);
1271 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001272 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001273 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001274}
Steve Naroff0cca7492008-05-01 22:18:59 +00001275
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001276/// \brief Expand a field designator that refers to a member of an
1277/// anonymous struct or union into a series of field designators that
1278/// refers to the field within the appropriate subobject.
1279///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001280static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001281 DesignatedInitExpr *DIE,
1282 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001283 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001284 typedef DesignatedInitExpr::Designator Designator;
1285
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001286 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001287 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001288 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1289 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1290 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001291 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001292 DIE->getDesignator(DesigIdx)->getDotLoc(),
1293 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1294 else
1295 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1296 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001297 assert(isa<FieldDecl>(*PI));
1298 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001299 }
1300
1301 // Expand the current designator into the set of replacement
1302 // designators, so we have a full subobject path down to where the
1303 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001304 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001305 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001306}
Mike Stump1eb44332009-09-09 15:08:12 +00001307
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001308/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001309/// corresponds to FieldName.
1310static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1311 IdentifierInfo *FieldName) {
1312 assert(AnonField->isAnonymousStructOrUnion());
1313 Decl *NextDecl = AnonField->getNextDeclInContext();
1314 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1315 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1316 return IF;
1317 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001318 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001319 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001320}
1321
Douglas Gregor05c13a32009-01-22 00:58:24 +00001322/// @brief Check the well-formedness of a C99 designated initializer.
1323///
1324/// Determines whether the designated initializer @p DIE, which
1325/// resides at the given @p Index within the initializer list @p
1326/// IList, is well-formed for a current object of type @p DeclType
1327/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001328/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001329/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001330///
1331/// @param IList The initializer list in which this designated
1332/// initializer occurs.
1333///
Douglas Gregor71199712009-04-15 04:56:10 +00001334/// @param DIE The designated initializer expression.
1335///
1336/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001337///
1338/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1339/// into which the designation in @p DIE should refer.
1340///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001341/// @param NextField If non-NULL and the first designator in @p DIE is
1342/// a field, this will be set to the field declaration corresponding
1343/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001344///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001345/// @param NextElementIndex If non-NULL and the first designator in @p
1346/// DIE is an array designator or GNU array-range designator, this
1347/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001348///
1349/// @param Index Index into @p IList where the designated initializer
1350/// @p DIE occurs.
1351///
Douglas Gregor4c678342009-01-28 21:54:33 +00001352/// @param StructuredList The initializer list expression that
1353/// describes all of the subobject initializers in the order they'll
1354/// actually be initialized.
1355///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001356/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001357bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001358InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001359 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001360 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001361 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001362 QualType &CurrentObjectType,
1363 RecordDecl::field_iterator *NextField,
1364 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 unsigned &Index,
1366 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001367 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001368 bool FinishSubobjectInit,
1369 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001370 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001371 // Check the actual initialization for the designated object type.
1372 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001373
1374 // Temporarily remove the designator expression from the
1375 // initializer list that the child calls see, so that we don't try
1376 // to re-process the designator.
1377 unsigned OldIndex = Index;
1378 IList->setInit(OldIndex, DIE->getInit());
1379
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001380 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001382
1383 // Restore the designated initializer expression in the syntactic
1384 // form of the initializer list.
1385 if (IList->getInit(OldIndex) != DIE->getInit())
1386 DIE->setInit(IList->getInit(OldIndex));
1387 IList->setInit(OldIndex, DIE);
1388
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001389 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001390 }
1391
Douglas Gregor71199712009-04-15 04:56:10 +00001392 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001393 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 "Need a non-designated initializer list to start from");
1395
Douglas Gregor71199712009-04-15 04:56:10 +00001396 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001397 // Determine the structural initializer list that corresponds to the
1398 // current subobject.
1399 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001400 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001401 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 SourceRange(D->getStartLocation(),
1403 DIE->getSourceRange().getEnd()));
1404 assert(StructuredList && "Expected a structured initializer list");
1405
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 if (D->isFieldDesignator()) {
1407 // C99 6.7.8p7:
1408 //
1409 // If a designator has the form
1410 //
1411 // . identifier
1412 //
1413 // then the current object (defined below) shall have
1414 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001415 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001416 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001417 if (!RT) {
1418 SourceLocation Loc = D->getDotLoc();
1419 if (Loc.isInvalid())
1420 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001421 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1422 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001423 ++Index;
1424 return true;
1425 }
1426
Douglas Gregor4c678342009-01-28 21:54:33 +00001427 // Note: we perform a linear search of the fields here, despite
1428 // the fact that we have a faster lookup method, because we always
1429 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001430 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001431 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001432 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001433 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001434 Field = RT->getDecl()->field_begin(),
1435 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001436 for (; Field != FieldEnd; ++Field) {
1437 if (Field->isUnnamedBitfield())
1438 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001439
Francois Picheta0e27f02010-12-22 03:46:10 +00001440 // If we find a field representing an anonymous field, look in the
1441 // IndirectFieldDecl that follow for the designated initializer.
1442 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1443 if (IndirectFieldDecl *IF =
1444 FindIndirectFieldDesignator(*Field, FieldName)) {
1445 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1446 D = DIE->getDesignator(DesigIdx);
1447 break;
1448 }
1449 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001450 if (KnownField && KnownField == *Field)
1451 break;
1452 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001453 break;
1454
1455 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001456 }
1457
Douglas Gregor4c678342009-01-28 21:54:33 +00001458 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001459 // There was no normal field in the struct with the designated
1460 // name. Perform another lookup for this name, which may find
1461 // something that we can't designate (e.g., a member function),
1462 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001463 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001464 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001465 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001466 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001467 // Name lookup didn't find anything. Determine whether this
1468 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001470 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001471 TypoCorrection Corrected = SemaRef.CorrectTypo(
1472 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1473 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1474 RT->getDecl(), false, Sema::CTC_NoKeywords);
1475 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001476 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001477 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001478 std::string CorrectedStr(
1479 Corrected.getAsString(SemaRef.getLangOptions()));
1480 std::string CorrectedQuotedStr(
1481 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001482 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001483 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001484 << FieldName << CurrentObjectType << CorrectedQuotedStr
1485 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001487 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001488 } else {
1489 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1490 << FieldName << CurrentObjectType;
1491 ++Index;
1492 return true;
1493 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001494 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001496 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001497 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001498 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001499 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001500 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001501 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001502 ++Index;
1503 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001504 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001505
Francois Picheta0e27f02010-12-22 03:46:10 +00001506 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001507 // The replacement field comes from typo correction; find it
1508 // in the list of fields.
1509 FieldIndex = 0;
1510 Field = RT->getDecl()->field_begin();
1511 for (; Field != FieldEnd; ++Field) {
1512 if (Field->isUnnamedBitfield())
1513 continue;
1514
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001515 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001516 Field->getIdentifier() == ReplacementField->getIdentifier())
1517 break;
1518
1519 ++FieldIndex;
1520 }
1521 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001522 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001523
1524 // All of the fields of a union are located at the same place in
1525 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001526 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001527 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001528 StructuredList->setInitializedFieldInUnion(*Field);
1529 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001530
Douglas Gregor54001c12011-06-29 21:51:31 +00001531 // Make sure we can use this declaration.
1532 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1533 ++Index;
1534 return true;
1535 }
1536
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001538 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Douglas Gregor4c678342009-01-28 21:54:33 +00001540 // Make sure that our non-designated initializer list has space
1541 // for a subobject corresponding to this field.
1542 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001543 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001544
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001545 // This designator names a flexible array member.
1546 if (Field->getType()->isIncompleteArrayType()) {
1547 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001548 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001549 // We can't designate an object within the flexible array
1550 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001551 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001552 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001553 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001554 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001555 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001556 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001557 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001558 << *Field;
1559 Invalid = true;
1560 }
1561
Chris Lattner9046c222010-10-10 17:49:49 +00001562 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1563 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001564 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001565 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001566 diag::err_flexible_array_init_needs_braces)
1567 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001568 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001569 << *Field;
1570 Invalid = true;
1571 }
1572
1573 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001574 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001575 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001576 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001577 diag::err_flexible_array_init_nonempty)
1578 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001579 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001580 << *Field;
1581 Invalid = true;
1582 }
1583
1584 if (Invalid) {
1585 ++Index;
1586 return true;
1587 }
1588
1589 // Initialize the array.
1590 bool prevHadError = hadError;
1591 unsigned newStructuredIndex = FieldIndex;
1592 unsigned OldIndex = Index;
1593 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001594
1595 InitializedEntity MemberEntity =
1596 InitializedEntity::InitializeMember(*Field, &Entity);
1597 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001598 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001599
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001600 IList->setInit(OldIndex, DIE);
1601 if (hadError && !prevHadError) {
1602 ++Field;
1603 ++FieldIndex;
1604 if (NextField)
1605 *NextField = Field;
1606 StructuredIndex = FieldIndex;
1607 return true;
1608 }
1609 } else {
1610 // Recurse to check later designated subobjects.
1611 QualType FieldType = (*Field)->getType();
1612 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001613
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001614 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001615 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001616 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1617 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001618 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001619 true, false))
1620 return true;
1621 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001622
1623 // Find the position of the next field to be initialized in this
1624 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001625 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001626 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001627
1628 // If this the first designator, our caller will continue checking
1629 // the rest of this struct/class/union subobject.
1630 if (IsFirstDesignator) {
1631 if (NextField)
1632 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001633 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001634 return false;
1635 }
1636
Douglas Gregor34e79462009-01-28 23:36:17 +00001637 if (!FinishSubobjectInit)
1638 return false;
1639
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001640 // We've already initialized something in the union; we're done.
1641 if (RT->getDecl()->isUnion())
1642 return hadError;
1643
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001644 // Check the remaining fields within this class/struct/union subobject.
1645 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001646
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001647 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001648 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001649 return hadError && !prevHadError;
1650 }
1651
1652 // C99 6.7.8p6:
1653 //
1654 // If a designator has the form
1655 //
1656 // [ constant-expression ]
1657 //
1658 // then the current object (defined below) shall have array
1659 // type and the expression shall be an integer constant
1660 // expression. If the array is of unknown size, any
1661 // nonnegative value is valid.
1662 //
1663 // Additionally, cope with the GNU extension that permits
1664 // designators of the form
1665 //
1666 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001667 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001668 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001669 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001670 << CurrentObjectType;
1671 ++Index;
1672 return true;
1673 }
1674
1675 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001676 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1677 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001678 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001679 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001680 DesignatedEndIndex = DesignatedStartIndex;
1681 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001682 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001683
Mike Stump1eb44332009-09-09 15:08:12 +00001684 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001685 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001686 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001687 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001688 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001689
Chris Lattnere0fd8322011-02-19 22:28:58 +00001690 // Codegen can't handle evaluating array range designators that have side
1691 // effects, because we replicate the AST value for each initialized element.
1692 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1693 // elements with something that has a side effect, so codegen can emit an
1694 // "error unsupported" error instead of miscompiling the app.
1695 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1696 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001697 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001698 }
1699
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001700 if (isa<ConstantArrayType>(AT)) {
1701 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001702 DesignatedStartIndex
1703 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001704 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001705 DesignatedEndIndex
1706 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001707 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1708 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001709 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001710 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001711 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001712 << IndexExpr->getSourceRange();
1713 ++Index;
1714 return true;
1715 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001716 } else {
1717 // Make sure the bit-widths and signedness match.
1718 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001719 DesignatedEndIndex
1720 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001721 else if (DesignatedStartIndex.getBitWidth() <
1722 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001723 DesignatedStartIndex
1724 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001725 DesignatedStartIndex.setIsUnsigned(true);
1726 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregor4c678342009-01-28 21:54:33 +00001729 // Make sure that our non-designated initializer list has space
1730 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001731 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001732 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001733 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001734
Douglas Gregor34e79462009-01-28 23:36:17 +00001735 // Repeatedly perform subobject initializations in the range
1736 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001737
Douglas Gregor34e79462009-01-28 23:36:17 +00001738 // Move to the next designator
1739 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1740 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001742 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001743 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001744
Douglas Gregor34e79462009-01-28 23:36:17 +00001745 while (DesignatedStartIndex <= DesignatedEndIndex) {
1746 // Recurse to check later designated subobjects.
1747 QualType ElementType = AT->getElementType();
1748 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001750 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001751 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1752 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001753 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001754 (DesignatedStartIndex == DesignatedEndIndex),
1755 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001756 return true;
1757
1758 // Move to the next index in the array that we'll be initializing.
1759 ++DesignatedStartIndex;
1760 ElementIndex = DesignatedStartIndex.getZExtValue();
1761 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001762
1763 // If this the first designator, our caller will continue checking
1764 // the rest of this array subobject.
1765 if (IsFirstDesignator) {
1766 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001767 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001768 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001769 return false;
1770 }
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor34e79462009-01-28 23:36:17 +00001772 if (!FinishSubobjectInit)
1773 return false;
1774
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001775 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001776 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001778 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001780 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001781}
1782
Douglas Gregor4c678342009-01-28 21:54:33 +00001783// Get the structured initializer list for a subobject of type
1784// @p CurrentObjectType.
1785InitListExpr *
1786InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1787 QualType CurrentObjectType,
1788 InitListExpr *StructuredList,
1789 unsigned StructuredIndex,
1790 SourceRange InitRange) {
1791 Expr *ExistingInit = 0;
1792 if (!StructuredList)
1793 ExistingInit = SyntacticToSemantic[IList];
1794 else if (StructuredIndex < StructuredList->getNumInits())
1795 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1798 return Result;
1799
1800 if (ExistingInit) {
1801 // We are creating an initializer list that initializes the
1802 // subobjects of the current object, but there was already an
1803 // initialization that completely initialized the current
1804 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001805 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001806 // struct X { int a, b; };
1807 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001808 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001809 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1810 // designated initializer re-initializes the whole
1811 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001812 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001813 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001814 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001815 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001816 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001817 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001818 << ExistingInit->getSourceRange();
1819 }
1820
Mike Stump1eb44332009-09-09 15:08:12 +00001821 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001822 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1823 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001824 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001825
Douglas Gregor63982352010-07-13 18:40:04 +00001826 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001827
Douglas Gregorfa219202009-03-20 23:58:33 +00001828 // Pre-allocate storage for the structured initializer list.
1829 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001830 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001831 bool GotNumInits = false;
1832 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00001833 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001834 GotNumInits = true;
1835 } else if (Index < IList->getNumInits()) {
1836 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00001837 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001838 GotNumInits = true;
1839 }
Douglas Gregor08457732009-03-21 18:13:52 +00001840 }
1841
Mike Stump1eb44332009-09-09 15:08:12 +00001842 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001843 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1844 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1845 NumElements = CAType->getSize().getZExtValue();
1846 // Simple heuristic so that we don't allocate a very large
1847 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001848 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001849 NumElements = 0;
1850 }
John McCall183700f2009-09-21 23:43:11 +00001851 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001852 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001853 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001854 RecordDecl *RDecl = RType->getDecl();
1855 if (RDecl->isUnion())
1856 NumElements = 1;
1857 else
Mike Stump1eb44332009-09-09 15:08:12 +00001858 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001859 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001860 }
1861
Douglas Gregor08457732009-03-21 18:13:52 +00001862 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001863 NumElements = IList->getNumInits();
1864
Ted Kremenek709210f2010-04-13 23:39:13 +00001865 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001866
Douglas Gregor4c678342009-01-28 21:54:33 +00001867 // Link this new initializer list into the structured initializer
1868 // lists.
1869 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001870 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001871 else {
1872 Result->setSyntacticForm(IList);
1873 SyntacticToSemantic[IList] = Result;
1874 }
1875
1876 return Result;
1877}
1878
1879/// Update the initializer at index @p StructuredIndex within the
1880/// structured initializer list to the value @p expr.
1881void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1882 unsigned &StructuredIndex,
1883 Expr *expr) {
1884 // No structured initializer list to update
1885 if (!StructuredList)
1886 return;
1887
Ted Kremenek709210f2010-04-13 23:39:13 +00001888 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1889 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001890 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001891 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001892 diag::warn_initializer_overrides)
1893 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001894 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001895 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001896 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001897 << PrevInit->getSourceRange();
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregor4c678342009-01-28 21:54:33 +00001900 ++StructuredIndex;
1901}
1902
Douglas Gregor05c13a32009-01-22 00:58:24 +00001903/// Check that the given Index expression is a valid array designator
1904/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001905/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001906/// and produces a reasonable diagnostic if there is a
1907/// failure. Returns true if there was an error, false otherwise. If
1908/// everything went okay, Value will receive the value of the constant
1909/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001910static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001911CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001912 SourceLocation Loc = Index->getSourceRange().getBegin();
1913
1914 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001915 if (S.VerifyIntegerConstantExpression(Index, &Value))
1916 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001917
Chris Lattner3bf68932009-04-25 21:59:05 +00001918 if (Value.isSigned() && Value.isNegative())
1919 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001920 << Value.toString(10) << Index->getSourceRange();
1921
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001922 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001923 return false;
1924}
1925
John McCall60d7b3a2010-08-24 06:29:42 +00001926ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001927 SourceLocation Loc,
1928 bool GNUSyntax,
1929 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001930 typedef DesignatedInitExpr::Designator ASTDesignator;
1931
1932 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001933 SmallVector<ASTDesignator, 32> Designators;
1934 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001935
1936 // Build designators and check array designator expressions.
1937 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1938 const Designator &D = Desig.getDesignator(Idx);
1939 switch (D.getKind()) {
1940 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001941 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001942 D.getFieldLoc()));
1943 break;
1944
1945 case Designator::ArrayDesignator: {
1946 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1947 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001948 if (!Index->isTypeDependent() &&
1949 !Index->isValueDependent() &&
1950 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001951 Invalid = true;
1952 else {
1953 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001954 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001955 D.getRBracketLoc()));
1956 InitExpressions.push_back(Index);
1957 }
1958 break;
1959 }
1960
1961 case Designator::ArrayRangeDesignator: {
1962 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1963 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1964 llvm::APSInt StartValue;
1965 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001966 bool StartDependent = StartIndex->isTypeDependent() ||
1967 StartIndex->isValueDependent();
1968 bool EndDependent = EndIndex->isTypeDependent() ||
1969 EndIndex->isValueDependent();
1970 if ((!StartDependent &&
1971 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1972 (!EndDependent &&
1973 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001974 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001975 else {
1976 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001977 if (StartDependent || EndDependent) {
1978 // Nothing to compute.
1979 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001980 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001981 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001982 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001983
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001984 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001985 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001986 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001987 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1988 Invalid = true;
1989 } else {
1990 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001991 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001992 D.getEllipsisLoc(),
1993 D.getRBracketLoc()));
1994 InitExpressions.push_back(StartIndex);
1995 InitExpressions.push_back(EndIndex);
1996 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001997 }
1998 break;
1999 }
2000 }
2001 }
2002
2003 if (Invalid || Init.isInvalid())
2004 return ExprError();
2005
2006 // Clear out the expressions within the designation.
2007 Desig.ClearExprs(*this);
2008
2009 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002010 = DesignatedInitExpr::Create(Context,
2011 Designators.data(), Designators.size(),
2012 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002013 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002015 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002016 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2017 << DIE->getSourceRange();
2018 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002019 Diag(DIE->getLocStart(), diag::ext_designated_init)
2020 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002021
Douglas Gregor05c13a32009-01-22 00:58:24 +00002022 return Owned(DIE);
2023}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002024
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002025bool Sema::CheckInitList(const InitializedEntity &Entity,
2026 InitListExpr *&InitList, QualType &DeclType) {
2027 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002028 if (!CheckInitList.HadError())
2029 InitList = CheckInitList.getFullyStructuredList();
2030
2031 return CheckInitList.HadError();
2032}
Douglas Gregor87fd7032009-02-02 17:43:21 +00002033
Douglas Gregor20093b42009-12-09 23:02:17 +00002034//===----------------------------------------------------------------------===//
2035// Initialization entity
2036//===----------------------------------------------------------------------===//
2037
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002038InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002039 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002040 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002041{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002042 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2043 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002044 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002045 } else {
2046 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002047 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002048 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002049}
2050
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002051InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002052 CXXBaseSpecifier *Base,
2053 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002054{
2055 InitializedEntity Result;
2056 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002057 Result.Base = reinterpret_cast<uintptr_t>(Base);
2058 if (IsInheritedVirtualBase)
2059 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060
Douglas Gregord6542d82009-12-22 15:35:07 +00002061 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002062 return Result;
2063}
2064
Douglas Gregor99a2e602009-12-16 01:38:02 +00002065DeclarationName InitializedEntity::getName() const {
2066 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002067 case EK_Parameter: {
2068 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2069 return (D ? D->getDeclName() : DeclarationName());
2070 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002071
2072 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002073 case EK_Member:
2074 return VariableOrMember->getDeclName();
2075
2076 case EK_Result:
2077 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002078 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002079 case EK_Temporary:
2080 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002081 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002082 case EK_ArrayElement:
2083 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002084 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002085 return DeclarationName();
2086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
Douglas Gregor99a2e602009-12-16 01:38:02 +00002088 // Silence GCC warning
2089 return DeclarationName();
2090}
2091
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002092DeclaratorDecl *InitializedEntity::getDecl() const {
2093 switch (getKind()) {
2094 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002095 case EK_Member:
2096 return VariableOrMember;
2097
John McCallf85e1932011-06-15 23:02:42 +00002098 case EK_Parameter:
2099 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2100
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002101 case EK_Result:
2102 case EK_Exception:
2103 case EK_New:
2104 case EK_Temporary:
2105 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002106 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002107 case EK_ArrayElement:
2108 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002109 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002110 return 0;
2111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002113 // Silence GCC warning
2114 return 0;
2115}
2116
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002117bool InitializedEntity::allowsNRVO() const {
2118 switch (getKind()) {
2119 case EK_Result:
2120 case EK_Exception:
2121 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002122
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002123 case EK_Variable:
2124 case EK_Parameter:
2125 case EK_Member:
2126 case EK_New:
2127 case EK_Temporary:
2128 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002129 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002130 case EK_ArrayElement:
2131 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002132 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002133 break;
2134 }
2135
2136 return false;
2137}
2138
Douglas Gregor20093b42009-12-09 23:02:17 +00002139//===----------------------------------------------------------------------===//
2140// Initialization sequence
2141//===----------------------------------------------------------------------===//
2142
2143void InitializationSequence::Step::Destroy() {
2144 switch (Kind) {
2145 case SK_ResolveAddressOfOverloadedFunction:
2146 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002147 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002148 case SK_CastDerivedToBaseLValue:
2149 case SK_BindReference:
2150 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002151 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002152 case SK_UserConversion:
2153 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002154 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002155 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002156 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002157 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002158 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002159 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002160 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002161 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002162 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002163 case SK_PassByIndirectCopyRestore:
2164 case SK_PassByIndirectRestore:
2165 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002166 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167
Douglas Gregor20093b42009-12-09 23:02:17 +00002168 case SK_ConversionSequence:
2169 delete ICS;
2170 }
2171}
2172
Douglas Gregorb70cf442010-03-26 20:14:36 +00002173bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002174 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002175}
2176
2177bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002178 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002179 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180
Douglas Gregorb70cf442010-03-26 20:14:36 +00002181 switch (getFailureKind()) {
2182 case FK_TooManyInitsForReference:
2183 case FK_ArrayNeedsInitList:
2184 case FK_ArrayNeedsInitListOrStringLiteral:
2185 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2186 case FK_NonConstLValueReferenceBindingToTemporary:
2187 case FK_NonConstLValueReferenceBindingToUnrelated:
2188 case FK_RValueReferenceBindingToLValue:
2189 case FK_ReferenceInitDropsQualifiers:
2190 case FK_ReferenceInitFailed:
2191 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002192 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002193 case FK_TooManyInitsForScalar:
2194 case FK_ReferenceBindingToInitList:
2195 case FK_InitListBadDestinationType:
2196 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002197 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002198 case FK_ArrayTypeMismatch:
2199 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002200 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201
Douglas Gregorb70cf442010-03-26 20:14:36 +00002202 case FK_ReferenceInitOverloadFailed:
2203 case FK_UserConversionOverloadFailed:
2204 case FK_ConstructorOverloadFailed:
2205 return FailedOverloadResult == OR_Ambiguous;
2206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207
Douglas Gregorb70cf442010-03-26 20:14:36 +00002208 return false;
2209}
2210
Douglas Gregord6e44a32010-04-16 22:09:46 +00002211bool InitializationSequence::isConstructorInitialization() const {
2212 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2213}
2214
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002215bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2216 const Expr *Initializer,
2217 bool *isInitializerConstant,
2218 APValue *ConstantValue) const {
2219 if (Steps.empty() || Initializer->isValueDependent())
2220 return false;
2221
2222 const Step &LastStep = Steps.back();
2223 if (LastStep.Kind != SK_ConversionSequence)
2224 return false;
2225
2226 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2227 const StandardConversionSequence *SCS = NULL;
2228 switch (ICS.getKind()) {
2229 case ImplicitConversionSequence::StandardConversion:
2230 SCS = &ICS.Standard;
2231 break;
2232 case ImplicitConversionSequence::UserDefinedConversion:
2233 SCS = &ICS.UserDefined.After;
2234 break;
2235 case ImplicitConversionSequence::AmbiguousConversion:
2236 case ImplicitConversionSequence::EllipsisConversion:
2237 case ImplicitConversionSequence::BadConversion:
2238 return false;
2239 }
2240
2241 // Check if SCS represents a narrowing conversion, according to C++0x
2242 // [dcl.init.list]p7:
2243 //
2244 // A narrowing conversion is an implicit conversion ...
2245 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2246 QualType FromType = SCS->getToType(0);
2247 QualType ToType = SCS->getToType(1);
2248 switch (PossibleNarrowing) {
2249 // * from a floating-point type to an integer type, or
2250 //
2251 // * from an integer type or unscoped enumeration type to a floating-point
2252 // type, except where the source is a constant expression and the actual
2253 // value after conversion will fit into the target type and will produce
2254 // the original value when converted back to the original type, or
2255 case ICK_Floating_Integral:
2256 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2257 *isInitializerConstant = false;
2258 return true;
2259 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2260 llvm::APSInt IntConstantValue;
2261 if (Initializer &&
2262 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2263 // Convert the integer to the floating type.
2264 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2265 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2266 llvm::APFloat::rmNearestTiesToEven);
2267 // And back.
2268 llvm::APSInt ConvertedValue = IntConstantValue;
2269 bool ignored;
2270 Result.convertToInteger(ConvertedValue,
2271 llvm::APFloat::rmTowardZero, &ignored);
2272 // If the resulting value is different, this was a narrowing conversion.
2273 if (IntConstantValue != ConvertedValue) {
2274 *isInitializerConstant = true;
2275 *ConstantValue = APValue(IntConstantValue);
2276 return true;
2277 }
2278 } else {
2279 // Variables are always narrowings.
2280 *isInitializerConstant = false;
2281 return true;
2282 }
2283 }
2284 return false;
2285
2286 // * from long double to double or float, or from double to float, except
2287 // where the source is a constant expression and the actual value after
2288 // conversion is within the range of values that can be represented (even
2289 // if it cannot be represented exactly), or
2290 case ICK_Floating_Conversion:
2291 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2292 // FromType is larger than ToType.
2293 Expr::EvalResult InitializerValue;
2294 // FIXME: Check whether Initializer is a constant expression according
2295 // to C++0x [expr.const], rather than just whether it can be folded.
2296 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2297 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2298 // Constant! (Except for FIXME above.)
2299 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2300 // Convert the source value into the target type.
2301 bool ignored;
2302 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2303 Ctx.getFloatTypeSemantics(ToType),
2304 llvm::APFloat::rmNearestTiesToEven, &ignored);
2305 // If there was no overflow, the source value is within the range of
2306 // values that can be represented.
2307 if (ConvertStatus & llvm::APFloat::opOverflow) {
2308 *isInitializerConstant = true;
2309 *ConstantValue = InitializerValue.Val;
2310 return true;
2311 }
2312 } else {
2313 *isInitializerConstant = false;
2314 return true;
2315 }
2316 }
2317 return false;
2318
2319 // * from an integer type or unscoped enumeration type to an integer type
2320 // that cannot represent all the values of the original type, except where
2321 // the source is a constant expression and the actual value after
2322 // conversion will fit into the target type and will produce the original
2323 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002324 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002325 case ICK_Integral_Conversion: {
2326 assert(FromType->isIntegralOrUnscopedEnumerationType());
2327 assert(ToType->isIntegralOrUnscopedEnumerationType());
2328 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2329 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2330 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2331 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2332
2333 if (FromWidth > ToWidth ||
2334 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2335 // Not all values of FromType can be represented in ToType.
2336 llvm::APSInt InitializerValue;
2337 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2338 *isInitializerConstant = true;
2339 *ConstantValue = APValue(InitializerValue);
2340
2341 // Add a bit to the InitializerValue so we don't have to worry about
2342 // signed vs. unsigned comparisons.
2343 InitializerValue = InitializerValue.extend(
2344 InitializerValue.getBitWidth() + 1);
2345 // Convert the initializer to and from the target width and signed-ness.
2346 llvm::APSInt ConvertedValue = InitializerValue;
2347 ConvertedValue = ConvertedValue.trunc(ToWidth);
2348 ConvertedValue.setIsSigned(ToSigned);
2349 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2350 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2351 // If the result is different, this was a narrowing conversion.
2352 return ConvertedValue != InitializerValue;
2353 } else {
2354 // Variables are always narrowings.
2355 *isInitializerConstant = false;
2356 return true;
2357 }
2358 }
2359 return false;
2360 }
2361
2362 default:
2363 // Other kinds of conversions are not narrowings.
2364 return false;
2365 }
2366}
2367
Douglas Gregor20093b42009-12-09 23:02:17 +00002368void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002369 FunctionDecl *Function,
2370 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002371 Step S;
2372 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2373 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002374 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002375 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002376 Steps.push_back(S);
2377}
2378
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002379void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002380 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002381 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002382 switch (VK) {
2383 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2384 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2385 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002386 default: llvm_unreachable("No such category");
2387 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002388 S.Type = BaseType;
2389 Steps.push_back(S);
2390}
2391
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002392void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 bool BindingTemporary) {
2394 Step S;
2395 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2396 S.Type = T;
2397 Steps.push_back(S);
2398}
2399
Douglas Gregor523d46a2010-04-18 07:40:54 +00002400void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2401 Step S;
2402 S.Kind = SK_ExtraneousCopyToTemporary;
2403 S.Type = T;
2404 Steps.push_back(S);
2405}
2406
Eli Friedman03981012009-12-11 02:42:07 +00002407void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002408 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002409 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002410 Step S;
2411 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002412 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002413 S.Function.Function = Function;
2414 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002415 Steps.push_back(S);
2416}
2417
2418void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002419 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002420 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002421 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002422 switch (VK) {
2423 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002424 S.Kind = SK_QualificationConversionRValue;
2425 break;
John McCall5baba9d2010-08-25 10:28:54 +00002426 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002427 S.Kind = SK_QualificationConversionXValue;
2428 break;
John McCall5baba9d2010-08-25 10:28:54 +00002429 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002430 S.Kind = SK_QualificationConversionLValue;
2431 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002432 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002433 S.Type = Ty;
2434 Steps.push_back(S);
2435}
2436
2437void InitializationSequence::AddConversionSequenceStep(
2438 const ImplicitConversionSequence &ICS,
2439 QualType T) {
2440 Step S;
2441 S.Kind = SK_ConversionSequence;
2442 S.Type = T;
2443 S.ICS = new ImplicitConversionSequence(ICS);
2444 Steps.push_back(S);
2445}
2446
Douglas Gregord87b61f2009-12-10 17:56:55 +00002447void InitializationSequence::AddListInitializationStep(QualType T) {
2448 Step S;
2449 S.Kind = SK_ListInitialization;
2450 S.Type = T;
2451 Steps.push_back(S);
2452}
2453
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002454void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002455InitializationSequence::AddConstructorInitializationStep(
2456 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002457 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002458 QualType T) {
2459 Step S;
2460 S.Kind = SK_ConstructorInitialization;
2461 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002462 S.Function.Function = Constructor;
2463 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002464 Steps.push_back(S);
2465}
2466
Douglas Gregor71d17402009-12-15 00:01:57 +00002467void InitializationSequence::AddZeroInitializationStep(QualType T) {
2468 Step S;
2469 S.Kind = SK_ZeroInitialization;
2470 S.Type = T;
2471 Steps.push_back(S);
2472}
2473
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002474void InitializationSequence::AddCAssignmentStep(QualType T) {
2475 Step S;
2476 S.Kind = SK_CAssignment;
2477 S.Type = T;
2478 Steps.push_back(S);
2479}
2480
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002481void InitializationSequence::AddStringInitStep(QualType T) {
2482 Step S;
2483 S.Kind = SK_StringInit;
2484 S.Type = T;
2485 Steps.push_back(S);
2486}
2487
Douglas Gregor569c3162010-08-07 11:51:51 +00002488void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2489 Step S;
2490 S.Kind = SK_ObjCObjectConversion;
2491 S.Type = T;
2492 Steps.push_back(S);
2493}
2494
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002495void InitializationSequence::AddArrayInitStep(QualType T) {
2496 Step S;
2497 S.Kind = SK_ArrayInit;
2498 S.Type = T;
2499 Steps.push_back(S);
2500}
2501
John McCallf85e1932011-06-15 23:02:42 +00002502void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2503 bool shouldCopy) {
2504 Step s;
2505 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2506 : SK_PassByIndirectRestore);
2507 s.Type = type;
2508 Steps.push_back(s);
2509}
2510
2511void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2512 Step S;
2513 S.Kind = SK_ProduceObjCObject;
2514 S.Type = T;
2515 Steps.push_back(S);
2516}
2517
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002518void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002519 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002520 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002521 this->Failure = Failure;
2522 this->FailedOverloadResult = Result;
2523}
2524
2525//===----------------------------------------------------------------------===//
2526// Attempt initialization
2527//===----------------------------------------------------------------------===//
2528
John McCallf85e1932011-06-15 23:02:42 +00002529static void MaybeProduceObjCObject(Sema &S,
2530 InitializationSequence &Sequence,
2531 const InitializedEntity &Entity) {
2532 if (!S.getLangOptions().ObjCAutoRefCount) return;
2533
2534 /// When initializing a parameter, produce the value if it's marked
2535 /// __attribute__((ns_consumed)).
2536 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2537 if (!Entity.isParameterConsumed())
2538 return;
2539
2540 assert(Entity.getType()->isObjCRetainableType() &&
2541 "consuming an object of unretainable type?");
2542 Sequence.AddProduceObjCObjectStep(Entity.getType());
2543
2544 /// When initializing a return value, if the return type is a
2545 /// retainable type, then returns need to immediately retain the
2546 /// object. If an autorelease is required, it will be done at the
2547 /// last instant.
2548 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2549 if (!Entity.getType()->isObjCRetainableType())
2550 return;
2551
2552 Sequence.AddProduceObjCObjectStep(Entity.getType());
2553 }
2554}
2555
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002556/// \brief Attempt list initialization (C++0x [dcl.init.list])
2557static void TryListInitialization(Sema &S,
2558 const InitializedEntity &Entity,
2559 const InitializationKind &Kind,
2560 InitListExpr *InitList,
2561 InitializationSequence &Sequence) {
2562 // FIXME: We only perform rudimentary checking of list
2563 // initializations at this point, then assume that any list
2564 // initialization of an array, aggregate, or scalar will be
2565 // well-formed. When we actually "perform" list initialization, we'll
2566 // do all of the necessary checking. C++0x initializer lists will
2567 // force us to perform more checking here.
2568
2569 QualType DestType = Entity.getType();
2570
2571 // C++ [dcl.init]p13:
2572 // If T is a scalar type, then a declaration of the form
2573 //
2574 // T x = { a };
2575 //
2576 // is equivalent to
2577 //
2578 // T x = a;
2579 if (DestType->isScalarType()) {
2580 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2581 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2582 return;
2583 }
2584
2585 // Assume scalar initialization from a single value works.
2586 } else if (DestType->isAggregateType()) {
2587 // Assume aggregate initialization works.
2588 } else if (DestType->isVectorType()) {
2589 // Assume vector initialization works.
2590 } else if (DestType->isReferenceType()) {
2591 // FIXME: C++0x defines behavior for this.
2592 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2593 return;
2594 } else if (DestType->isRecordType()) {
2595 // FIXME: C++0x defines behavior for this
2596 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2597 }
2598
2599 // Add a general "list initialization" step.
2600 Sequence.AddListInitializationStep(DestType);
2601}
Douglas Gregor20093b42009-12-09 23:02:17 +00002602
2603/// \brief Try a reference initialization that involves calling a conversion
2604/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002605static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2606 const InitializedEntity &Entity,
2607 const InitializationKind &Kind,
2608 Expr *Initializer,
2609 bool AllowRValues,
2610 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002611 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2613 QualType T1 = cv1T1.getUnqualifiedType();
2614 QualType cv2T2 = Initializer->getType();
2615 QualType T2 = cv2T2.getUnqualifiedType();
2616
2617 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002618 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002619 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002620 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002621 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002622 ObjCConversion,
2623 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002624 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002625 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002626 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002627 (void)ObjCLifetimeConversion;
2628
Douglas Gregor20093b42009-12-09 23:02:17 +00002629 // Build the candidate set directly in the initialization sequence
2630 // structure, so that it will persist if we fail.
2631 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2632 CandidateSet.clear();
2633
2634 // Determine whether we are allowed to call explicit constructors or
2635 // explicit conversion operators.
2636 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002637
Douglas Gregor20093b42009-12-09 23:02:17 +00002638 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002639 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2640 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002641 // The type we're converting to is a class type. Enumerate its constructors
2642 // to see if there is a suitable conversion.
2643 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002644
Douglas Gregor20093b42009-12-09 23:02:17 +00002645 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002646 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002648 NamedDecl *D = *Con;
2649 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2650
Douglas Gregor20093b42009-12-09 23:02:17 +00002651 // Find the constructor (which may be a template).
2652 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002653 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002654 if (ConstructorTmpl)
2655 Constructor = cast<CXXConstructorDecl>(
2656 ConstructorTmpl->getTemplatedDecl());
2657 else
John McCall9aa472c2010-03-19 07:35:19 +00002658 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002659
Douglas Gregor20093b42009-12-09 23:02:17 +00002660 if (!Constructor->isInvalidDecl() &&
2661 Constructor->isConvertingConstructor(AllowExplicit)) {
2662 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002663 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002664 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002665 &Initializer, 1, CandidateSet,
2666 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002667 else
John McCall9aa472c2010-03-19 07:35:19 +00002668 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002669 &Initializer, 1, CandidateSet,
2670 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002672 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002673 }
John McCall572fc622010-08-17 07:23:57 +00002674 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2675 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002676
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002677 const RecordType *T2RecordType = 0;
2678 if ((T2RecordType = T2->getAs<RecordType>()) &&
2679 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002680 // The type we're converting from is a class type, enumerate its conversion
2681 // functions.
2682 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2683
John McCalleec51cf2010-01-20 00:46:10 +00002684 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002685 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002686 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2687 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002688 NamedDecl *D = *I;
2689 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2690 if (isa<UsingShadowDecl>(D))
2691 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692
Douglas Gregor20093b42009-12-09 23:02:17 +00002693 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2694 CXXConversionDecl *Conv;
2695 if (ConvTemplate)
2696 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2697 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002698 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699
Douglas Gregor20093b42009-12-09 23:02:17 +00002700 // If the conversion function doesn't return a reference type,
2701 // it can't be considered for this conversion unless we're allowed to
2702 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002703 // FIXME: Do we need to make sure that we only consider conversion
2704 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002705 // break recursion.
2706 if ((AllowExplicit || !Conv->isExplicit()) &&
2707 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2708 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002709 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002710 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002711 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002712 else
John McCall9aa472c2010-03-19 07:35:19 +00002713 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002714 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002715 }
2716 }
2717 }
John McCall572fc622010-08-17 07:23:57 +00002718 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2719 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002720
Douglas Gregor20093b42009-12-09 23:02:17 +00002721 SourceLocation DeclLoc = Initializer->getLocStart();
2722
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002723 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002724 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002725 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002726 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002727 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002728
Douglas Gregor20093b42009-12-09 23:02:17 +00002729 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002730
Chandler Carruth25ca4212011-02-25 19:41:05 +00002731 // This is the overload that will actually be used for the initialization, so
2732 // mark it as used.
2733 S.MarkDeclarationReferenced(DeclLoc, Function);
2734
Eli Friedman03981012009-12-11 02:42:07 +00002735 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002736 if (isa<CXXConversionDecl>(Function))
2737 T2 = Function->getResultType();
2738 else
2739 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002740
2741 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002742 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002743 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002744
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002745 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002746 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002747 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002748 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002749 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002750 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002751 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002752
Douglas Gregor20093b42009-12-09 23:02:17 +00002753 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002754 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002755 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002756 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002757 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002758 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002759 NewDerivedToBase, NewObjCConversion,
2760 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002761 if (NewRefRelationship == Sema::Ref_Incompatible) {
2762 // If the type we've converted to is not reference-related to the
2763 // type we're looking for, then there is another conversion step
2764 // we need to perform to produce a temporary of the right type
2765 // that we'll be binding to.
2766 ImplicitConversionSequence ICS;
2767 ICS.setStandard();
2768 ICS.Standard = Best->FinalConversion;
2769 T2 = ICS.Standard.getToType(2);
2770 Sequence.AddConversionSequenceStep(ICS, T2);
2771 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002772 Sequence.AddDerivedToBaseCastStep(
2773 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002774 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002775 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002776 else if (NewObjCConversion)
2777 Sequence.AddObjCObjectConversionStep(
2778 S.Context.getQualifiedType(T1,
2779 T2.getNonReferenceType().getQualifiers()));
2780
Douglas Gregor20093b42009-12-09 23:02:17 +00002781 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002782 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002783
Douglas Gregor20093b42009-12-09 23:02:17 +00002784 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2785 return OR_Success;
2786}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002787
2788/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2789static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002790 const InitializedEntity &Entity,
2791 const InitializationKind &Kind,
2792 Expr *Initializer,
2793 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002794 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002795 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002796 Qualifiers T1Quals;
2797 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002798 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002799 Qualifiers T2Quals;
2800 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002801 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002802
Douglas Gregor20093b42009-12-09 23:02:17 +00002803 // If the initializer is the address of an overloaded function, try
2804 // to resolve the overloaded function. If all goes well, T2 is the
2805 // type of the resulting function.
2806 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002807 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002808 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002809 T1,
2810 false,
2811 Found)) {
2812 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2813 cv2T2 = Fn->getType();
2814 T2 = cv2T2.getUnqualifiedType();
2815 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002816 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2817 return;
2818 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002819 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002820
Douglas Gregor20093b42009-12-09 23:02:17 +00002821 // Compute some basic properties of the types and the initializer.
2822 bool isLValueRef = DestType->isLValueReferenceType();
2823 bool isRValueRef = !isLValueRef;
2824 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002825 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002826 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002827 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002828 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002829 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002830 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002831
Douglas Gregor20093b42009-12-09 23:02:17 +00002832 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002834 // "cv2 T2" as follows:
2835 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002836 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002837 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002838 // Note the analogous bullet points for rvlaue refs to functions. Because
2839 // there are no function rvalues in C++, rvalue refs to functions are treated
2840 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002841 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002842 bool T1Function = T1->isFunctionType();
2843 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002845 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002846 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002847 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002849 // reference-compatible with "cv2 T2," or
2850 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002852 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002853 // can occur. However, we do pay attention to whether it is a bit-field
2854 // to decide whether we're actually binding to a temporary created from
2855 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002856 if (DerivedToBase)
2857 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002859 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002860 else if (ObjCConversion)
2861 Sequence.AddObjCObjectConversionStep(
2862 S.Context.getQualifiedType(T1, T2Quals));
2863
Chandler Carruth5535c382010-01-12 20:32:25 +00002864 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002865 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002866 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002867 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002868 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002869 return;
2870 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871
2872 // - has a class type (i.e., T2 is a class type), where T1 is not
2873 // reference-related to T2, and can be implicitly converted to an
2874 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2875 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002876 // applicable conversion functions (13.3.1.6) and choosing the best
2877 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002878 // If we have an rvalue ref to function type here, the rhs must be
2879 // an rvalue.
2880 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2881 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002882 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002883 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002884 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002885 Sequence);
2886 if (ConvOvlResult == OR_Success)
2887 return;
John McCall1d318332010-01-12 00:44:57 +00002888 if (ConvOvlResult != OR_No_Viable_Function) {
2889 Sequence.SetOverloadFailure(
2890 InitializationSequence::FK_ReferenceInitOverloadFailed,
2891 ConvOvlResult);
2892 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002893 }
2894 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002895
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002898 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002899 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002900 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2901 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2902 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002903 Sequence.SetOverloadFailure(
2904 InitializationSequence::FK_ReferenceInitOverloadFailed,
2905 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002906 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002907 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002908 ? (RefRelationship == Sema::Ref_Related
2909 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2910 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2911 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002912
Douglas Gregor20093b42009-12-09 23:02:17 +00002913 return;
2914 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002915
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002916 // - If the initializer expression
2917 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2918 // "cv1 T1" is reference-compatible with "cv2 T2"
2919 // Note: functions are handled below.
2920 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002921 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002922 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002923 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002924 (InitCategory.isXValue() ||
2925 (InitCategory.isPRValue() && T2->isRecordType()) ||
2926 (InitCategory.isPRValue() && T2->isArrayType()))) {
2927 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2928 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002929 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2930 // compiler the freedom to perform a copy here or bind to the
2931 // object, while C++0x requires that we bind directly to the
2932 // object. Hence, we always bind to the object without making an
2933 // extra copy. However, in C++03 requires that we check for the
2934 // presence of a suitable copy constructor:
2935 //
2936 // The constructor that would be used to make the copy shall
2937 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002938 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002939 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002940 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002941
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002942 if (DerivedToBase)
2943 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2944 ValueKind);
2945 else if (ObjCConversion)
2946 Sequence.AddObjCObjectConversionStep(
2947 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002948
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002949 if (T1Quals != T2Quals)
2950 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002952 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002953 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002954 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955
2956 // - has a class type (i.e., T2 is a class type), where T1 is not
2957 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002958 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2959 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002960 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002961 if (RefRelationship == Sema::Ref_Incompatible) {
2962 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2963 Kind, Initializer,
2964 /*AllowRValues=*/true,
2965 Sequence);
2966 if (ConvOvlResult)
2967 Sequence.SetOverloadFailure(
2968 InitializationSequence::FK_ReferenceInitOverloadFailed,
2969 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002970
Douglas Gregor20093b42009-12-09 23:02:17 +00002971 return;
2972 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002973
Douglas Gregor20093b42009-12-09 23:02:17 +00002974 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2975 return;
2976 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002977
2978 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002979 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002980 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002981 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002982
Douglas Gregor20093b42009-12-09 23:02:17 +00002983 // Determine whether we are allowed to call explicit constructors or
2984 // explicit conversion operators.
2985 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002986
2987 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2988
John McCallf85e1932011-06-15 23:02:42 +00002989 ImplicitConversionSequence ICS
2990 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00002991 /*SuppressUserConversions*/ false,
2992 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002993 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00002994 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2995 /*AllowObjCWritebackConversion=*/false);
2996
2997 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002998 // FIXME: Use the conversion function set stored in ICS to turn
2999 // this into an overloading ambiguity diagnostic. However, we need
3000 // to keep that set as an OverloadCandidateSet rather than as some
3001 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003002 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3003 Sequence.SetOverloadFailure(
3004 InitializationSequence::FK_ReferenceInitOverloadFailed,
3005 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003006 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3007 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003008 else
3009 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003010 return;
John McCallf85e1932011-06-15 23:02:42 +00003011 } else {
3012 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003013 }
3014
3015 // [...] If T1 is reference-related to T2, cv1 must be the
3016 // same cv-qualification as, or greater cv-qualification
3017 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003018 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3019 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003020 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003021 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003022 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3023 return;
3024 }
3025
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003026 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003027 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003028 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003029 InitCategory.isLValue()) {
3030 Sequence.SetFailed(
3031 InitializationSequence::FK_RValueReferenceBindingToLValue);
3032 return;
3033 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003034
Douglas Gregor20093b42009-12-09 23:02:17 +00003035 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3036 return;
3037}
3038
3039/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003040/// (C++ [dcl.init.string], C99 6.7.8).
3041static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003042 const InitializedEntity &Entity,
3043 const InitializationKind &Kind,
3044 Expr *Initializer,
3045 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003046 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003047}
3048
Douglas Gregor20093b42009-12-09 23:02:17 +00003049/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3050/// enumerates the constructors of the initialized entity and performs overload
3051/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003052static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003053 const InitializedEntity &Entity,
3054 const InitializationKind &Kind,
3055 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003056 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003057 InitializationSequence &Sequence) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003058 // Build the candidate set directly in the initialization sequence
3059 // structure, so that it will persist if we fail.
3060 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3061 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003062
Douglas Gregor51c56d62009-12-14 20:49:26 +00003063 // Determine whether we are allowed to call explicit constructors or
3064 // explicit conversion operators.
3065 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3066 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003067 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003068
3069 // The type we're constructing needs to be complete.
3070 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003071 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003072 return;
3073 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003074
Douglas Gregor51c56d62009-12-14 20:49:26 +00003075 // The type we're converting to is a class type. Enumerate its constructors
3076 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003077 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003078 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003079 CXXRecordDecl *DestRecordDecl
3080 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003081
Douglas Gregor51c56d62009-12-14 20:49:26 +00003082 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003083 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003084 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003085 NamedDecl *D = *Con;
3086 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003087 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003088
Douglas Gregor51c56d62009-12-14 20:49:26 +00003089 // Find the constructor (which may be a template).
3090 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003091 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003092 if (ConstructorTmpl)
3093 Constructor = cast<CXXConstructorDecl>(
3094 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003095 else {
John McCall9aa472c2010-03-19 07:35:19 +00003096 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003097
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003099 // suppress user-defined conversions on the arguments.
3100 // FIXME: Move constructors?
3101 if (Kind.getKind() == InitializationKind::IK_Copy &&
3102 Constructor->isCopyConstructor())
3103 SuppressUserConversions = true;
3104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003105
Douglas Gregor51c56d62009-12-14 20:49:26 +00003106 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003107 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003108 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003109 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003110 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003111 Args, NumArgs, CandidateSet,
3112 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003113 else
John McCall9aa472c2010-03-19 07:35:19 +00003114 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003115 Args, NumArgs, CandidateSet,
3116 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003117 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 }
3119
Douglas Gregor51c56d62009-12-14 20:49:26 +00003120 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121
3122 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003123 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003125 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003126 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003128 Result);
3129 return;
3130 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003131
3132 // C++0x [dcl.init]p6:
3133 // If a program calls for the default initialization of an object
3134 // of a const-qualified type T, T shall be a class type with a
3135 // user-provided default constructor.
3136 if (Kind.getKind() == InitializationKind::IK_Default &&
3137 Entity.getType().isConstQualified() &&
3138 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3139 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3140 return;
3141 }
3142
Douglas Gregor51c56d62009-12-14 20:49:26 +00003143 // Add the constructor initialization step. Any cv-qualification conversion is
3144 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003145 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003146 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003147 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003148 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003149}
3150
Douglas Gregor71d17402009-12-15 00:01:57 +00003151/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003152static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003153 const InitializedEntity &Entity,
3154 const InitializationKind &Kind,
3155 InitializationSequence &Sequence) {
3156 // C++ [dcl.init]p5:
3157 //
3158 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003159 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160
Douglas Gregor71d17402009-12-15 00:01:57 +00003161 // -- if T is an array type, then each element is value-initialized;
3162 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3163 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164
Douglas Gregor71d17402009-12-15 00:01:57 +00003165 if (const RecordType *RT = T->getAs<RecordType>()) {
3166 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3167 // -- if T is a class type (clause 9) with a user-declared
3168 // constructor (12.1), then the default constructor for T is
3169 // called (and the initialization is ill-formed if T has no
3170 // accessible default constructor);
3171 //
3172 // FIXME: we really want to refer to a single subobject of the array,
3173 // but Entity doesn't have a way to capture that (yet).
3174 if (ClassDecl->hasUserDeclaredConstructor())
3175 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003176
Douglas Gregor16006c92009-12-16 18:50:27 +00003177 // -- if T is a (possibly cv-qualified) non-union class type
3178 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003179 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003180 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003181 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003182 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003183 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003184 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003185 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003186 }
3187 }
3188
Douglas Gregord6542d82009-12-22 15:35:07 +00003189 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003190}
3191
Douglas Gregor99a2e602009-12-16 01:38:02 +00003192/// \brief Attempt default initialization (C++ [dcl.init]p6).
3193static void TryDefaultInitialization(Sema &S,
3194 const InitializedEntity &Entity,
3195 const InitializationKind &Kind,
3196 InitializationSequence &Sequence) {
3197 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003198
Douglas Gregor99a2e602009-12-16 01:38:02 +00003199 // C++ [dcl.init]p6:
3200 // To default-initialize an object of type T means:
3201 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003202 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3203
Douglas Gregor99a2e602009-12-16 01:38:02 +00003204 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3205 // constructor for T is called (and the initialization is ill-formed if
3206 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003207 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003208 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3209 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211
Douglas Gregor99a2e602009-12-16 01:38:02 +00003212 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213
Douglas Gregor99a2e602009-12-16 01:38:02 +00003214 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003216 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003217 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003218 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003219 return;
3220 }
3221
3222 // If the destination type has a lifetime property, zero-initialize it.
3223 if (DestType.getQualifiers().hasObjCLifetime()) {
3224 Sequence.AddZeroInitializationStep(Entity.getType());
3225 return;
3226 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003227}
3228
Douglas Gregor20093b42009-12-09 23:02:17 +00003229/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3230/// which enumerates all conversion functions and performs overload resolution
3231/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003233 const InitializedEntity &Entity,
3234 const InitializationKind &Kind,
3235 Expr *Initializer,
3236 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003237 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003238 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3239 QualType SourceType = Initializer->getType();
3240 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3241 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003242
Douglas Gregor4a520a22009-12-14 17:27:33 +00003243 // Build the candidate set directly in the initialization sequence
3244 // structure, so that it will persist if we fail.
3245 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3246 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003247
Douglas Gregor4a520a22009-12-14 17:27:33 +00003248 // Determine whether we are allowed to call explicit constructors or
3249 // explicit conversion operators.
3250 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003251
Douglas Gregor4a520a22009-12-14 17:27:33 +00003252 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3253 // The type we're converting to is a class type. Enumerate its constructors
3254 // to see if there is a suitable conversion.
3255 CXXRecordDecl *DestRecordDecl
3256 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003257
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003258 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003260 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003261 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003262 Con != ConEnd; ++Con) {
3263 NamedDecl *D = *Con;
3264 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003265
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003266 // Find the constructor (which may be a template).
3267 CXXConstructorDecl *Constructor = 0;
3268 FunctionTemplateDecl *ConstructorTmpl
3269 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003270 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003271 Constructor = cast<CXXConstructorDecl>(
3272 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003273 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003274 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003275
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003276 if (!Constructor->isInvalidDecl() &&
3277 Constructor->isConvertingConstructor(AllowExplicit)) {
3278 if (ConstructorTmpl)
3279 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3280 /*ExplicitArgs*/ 0,
3281 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003282 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003283 else
3284 S.AddOverloadCandidate(Constructor, FoundDecl,
3285 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003286 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003287 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003289 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003290 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003291
3292 SourceLocation DeclLoc = Initializer->getLocStart();
3293
Douglas Gregor4a520a22009-12-14 17:27:33 +00003294 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3295 // The type we're converting from is a class type, enumerate its conversion
3296 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003297
Eli Friedman33c2da92009-12-20 22:12:03 +00003298 // We can only enumerate the conversion functions for a complete type; if
3299 // the type isn't complete, simply skip this step.
3300 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3301 CXXRecordDecl *SourceRecordDecl
3302 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303
John McCalleec51cf2010-01-20 00:46:10 +00003304 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003305 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003306 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003307 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003308 I != E; ++I) {
3309 NamedDecl *D = *I;
3310 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3311 if (isa<UsingShadowDecl>(D))
3312 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313
Eli Friedman33c2da92009-12-20 22:12:03 +00003314 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3315 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003316 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003317 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003318 else
John McCall32daa422010-03-31 01:36:47 +00003319 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003320
Eli Friedman33c2da92009-12-20 22:12:03 +00003321 if (AllowExplicit || !Conv->isExplicit()) {
3322 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003323 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003324 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003325 CandidateSet);
3326 else
John McCall9aa472c2010-03-19 07:35:19 +00003327 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003328 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003329 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003330 }
3331 }
3332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333
3334 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003335 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003336 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003337 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003338 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003340 Result);
3341 return;
3342 }
John McCall1d318332010-01-12 00:44:57 +00003343
Douglas Gregor4a520a22009-12-14 17:27:33 +00003344 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003345 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregor4a520a22009-12-14 17:27:33 +00003347 if (isa<CXXConstructorDecl>(Function)) {
3348 // Add the user-defined conversion step. Any cv-qualification conversion is
3349 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003350 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003351 return;
3352 }
3353
3354 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003355 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003356 if (ConvType->getAs<RecordType>()) {
3357 // If we're converting to a class type, there may be an copy if
3358 // the resulting temporary object (possible to create an object of
3359 // a base class type). That copy is not a separate conversion, so
3360 // we just make a note of the actual destination type (possibly a
3361 // base class of the type returned by the conversion function) and
3362 // let the user-defined conversion step handle the conversion.
3363 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3364 return;
3365 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003366
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003367 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003368
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003369 // If the conversion following the call to the conversion function
3370 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003371 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3372 Best->FinalConversion.Third) {
3373 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003374 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003375 ICS.Standard = Best->FinalConversion;
3376 Sequence.AddConversionSequenceStep(ICS, DestType);
3377 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003378}
3379
John McCallf85e1932011-06-15 23:02:42 +00003380/// The non-zero enum values here are indexes into diagnostic alternatives.
3381enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3382
3383/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003384static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3385 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003386 // Skip parens.
3387 e = e->IgnoreParens();
3388
3389 // Skip address-of nodes.
3390 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3391 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003392 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003393
3394 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003395 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3396 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003397 case CK_Dependent:
3398 case CK_BitCast:
3399 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003400 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003401 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003402
3403 case CK_ArrayToPointerDecay:
3404 return IIK_nonscalar;
3405
3406 case CK_NullToPointer:
3407 return IIK_okay;
3408
3409 default:
3410 break;
3411 }
3412
3413 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003414 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3415 if (!isAddressOf) return IIK_nonlocal;
3416
3417 VarDecl *var;
3418 if (isa<DeclRefExpr>(e)) {
3419 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3420 if (!var) return IIK_nonlocal;
3421 } else {
3422 var = cast<BlockDeclRefExpr>(e)->getDecl();
3423 }
3424
3425 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003426
3427 // If we have a conditional operator, check both sides.
3428 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003429 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003430 return iik;
3431
John McCallc03fa492011-06-27 23:59:58 +00003432 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003433
3434 // These are never scalar.
3435 } else if (isa<ArraySubscriptExpr>(e)) {
3436 return IIK_nonscalar;
3437
3438 // Otherwise, it needs to be a null pointer constant.
3439 } else {
3440 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3441 ? IIK_okay : IIK_nonlocal);
3442 }
3443
3444 return IIK_nonlocal;
3445}
3446
3447/// Check whether the given expression is a valid operand for an
3448/// indirect copy/restore.
3449static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3450 assert(src->isRValue());
3451
John McCallc03fa492011-06-27 23:59:58 +00003452 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003453 if (iik == IIK_okay) return;
3454
3455 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3456 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3457 << src->getSourceRange();
3458}
3459
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003460/// \brief Determine whether we have compatible array types for the
3461/// purposes of GNU by-copy array initialization.
3462static bool hasCompatibleArrayTypes(ASTContext &Context,
3463 const ArrayType *Dest,
3464 const ArrayType *Source) {
3465 // If the source and destination array types are equivalent, we're
3466 // done.
3467 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3468 return true;
3469
3470 // Make sure that the element types are the same.
3471 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3472 return false;
3473
3474 // The only mismatch we allow is when the destination is an
3475 // incomplete array type and the source is a constant array type.
3476 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3477}
3478
John McCallf85e1932011-06-15 23:02:42 +00003479static bool tryObjCWritebackConversion(Sema &S,
3480 InitializationSequence &Sequence,
3481 const InitializedEntity &Entity,
3482 Expr *Initializer) {
3483 bool ArrayDecay = false;
3484 QualType ArgType = Initializer->getType();
3485 QualType ArgPointee;
3486 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3487 ArrayDecay = true;
3488 ArgPointee = ArgArrayType->getElementType();
3489 ArgType = S.Context.getPointerType(ArgPointee);
3490 }
3491
3492 // Handle write-back conversion.
3493 QualType ConvertedArgType;
3494 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3495 ConvertedArgType))
3496 return false;
3497
3498 // We should copy unless we're passing to an argument explicitly
3499 // marked 'out'.
3500 bool ShouldCopy = true;
3501 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3502 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3503
3504 // Do we need an lvalue conversion?
3505 if (ArrayDecay || Initializer->isGLValue()) {
3506 ImplicitConversionSequence ICS;
3507 ICS.setStandard();
3508 ICS.Standard.setAsIdentityConversion();
3509
3510 QualType ResultType;
3511 if (ArrayDecay) {
3512 ICS.Standard.First = ICK_Array_To_Pointer;
3513 ResultType = S.Context.getPointerType(ArgPointee);
3514 } else {
3515 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3516 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3517 }
3518
3519 Sequence.AddConversionSequenceStep(ICS, ResultType);
3520 }
3521
3522 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3523 return true;
3524}
3525
Douglas Gregor20093b42009-12-09 23:02:17 +00003526InitializationSequence::InitializationSequence(Sema &S,
3527 const InitializedEntity &Entity,
3528 const InitializationKind &Kind,
3529 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003530 unsigned NumArgs)
3531 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003532 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003533
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003535 // The semantics of initializers are as follows. The destination type is
3536 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003537 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003538 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003540 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003541
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003542 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003543 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3544 SequenceKind = DependentSequence;
3545 return;
3546 }
3547
Sebastian Redl7491c492011-06-05 13:59:11 +00003548 // Almost everything is a normal sequence.
3549 setSequenceKind(NormalSequence);
3550
John McCall241d5582010-12-07 22:54:16 +00003551 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003552 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3553 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3554 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003555 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003556 return;
3557 }
3558 Args[I] = Result.take();
3559 }
John McCall241d5582010-12-07 22:54:16 +00003560
Douglas Gregor20093b42009-12-09 23:02:17 +00003561 QualType SourceType;
3562 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003563 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003564 Initializer = Args[0];
3565 if (!isa<InitListExpr>(Initializer))
3566 SourceType = Initializer->getType();
3567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003568
3569 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003570 // list-initialized (8.5.4).
3571 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003572 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003573 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003574 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575
Douglas Gregor20093b42009-12-09 23:02:17 +00003576 // - If the destination type is a reference type, see 8.5.3.
3577 if (DestType->isReferenceType()) {
3578 // C++0x [dcl.init.ref]p1:
3579 // A variable declared to be a T& or T&&, that is, "reference to type T"
3580 // (8.3.2), shall be initialized by an object, or function, of type T or
3581 // by an object that can be converted into a T.
3582 // (Therefore, multiple arguments are not permitted.)
3583 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003584 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003585 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003586 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003587 return;
3588 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003589
Douglas Gregor20093b42009-12-09 23:02:17 +00003590 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003591 if (Kind.getKind() == InitializationKind::IK_Value ||
3592 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003593 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003594 return;
3595 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596
Douglas Gregor99a2e602009-12-16 01:38:02 +00003597 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003598 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003599 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003600 return;
3601 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003602
John McCallce6c9b72011-02-21 07:22:22 +00003603 // - If the destination type is an array of characters, an array of
3604 // char16_t, an array of char32_t, or an array of wchar_t, and the
3605 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003606 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003607 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003608 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3609 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003610 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003611 return;
3612 }
3613
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003614 // Note: as an GNU C extension, we allow initialization of an
3615 // array from a compound literal that creates an array of the same
3616 // type, so long as the initializer has no side effects.
3617 if (!S.getLangOptions().CPlusPlus && Initializer &&
3618 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3619 Initializer->getType()->isArrayType()) {
3620 const ArrayType *SourceAT
3621 = Context.getAsArrayType(Initializer->getType());
3622 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003623 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003624 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003625 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003626 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003627 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003628 }
3629 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003630 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003631 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003632 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003633
Douglas Gregor20093b42009-12-09 23:02:17 +00003634 return;
3635 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003636
John McCallf85e1932011-06-15 23:02:42 +00003637 // Determine whether we should consider writeback conversions for
3638 // Objective-C ARC.
3639 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3640 Entity.getKind() == InitializedEntity::EK_Parameter;
3641
3642 // We're at the end of the line for C: it's either a write-back conversion
3643 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003644 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003645 // If allowed, check whether this is an Objective-C writeback conversion.
3646 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003647 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003648 return;
3649 }
3650
3651 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003652 AddCAssignmentStep(DestType);
3653 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003654 return;
3655 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656
John McCallf85e1932011-06-15 23:02:42 +00003657 assert(S.getLangOptions().CPlusPlus);
3658
Douglas Gregor20093b42009-12-09 23:02:17 +00003659 // - If the destination type is a (possibly cv-qualified) class type:
3660 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661 // - If the initialization is direct-initialization, or if it is
3662 // copy-initialization where the cv-unqualified version of the
3663 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003664 // class of the destination, constructors are considered. [...]
3665 if (Kind.getKind() == InitializationKind::IK_Direct ||
3666 (Kind.getKind() == InitializationKind::IK_Copy &&
3667 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3668 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003669 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003670 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003672 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003674 // used) to a derived class thereof are enumerated as described in
3675 // 13.3.1.4, and the best one is chosen through overload resolution
3676 // (13.3).
3677 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003678 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003679 return;
3680 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003681
Douglas Gregor99a2e602009-12-16 01:38:02 +00003682 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003683 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003684 return;
3685 }
3686 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687
3688 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003689 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003690 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003691 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3692 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003693 return;
3694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695
Douglas Gregor20093b42009-12-09 23:02:17 +00003696 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003697 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003698 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003700 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003701
3702 ImplicitConversionSequence ICS
3703 = S.TryImplicitConversion(Initializer, Entity.getType(),
3704 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003705 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003706 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003707 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3708 allowObjCWritebackConversion);
3709
3710 if (ICS.isStandard() &&
3711 ICS.Standard.Second == ICK_Writeback_Conversion) {
3712 // Objective-C ARC writeback conversion.
3713
3714 // We should copy unless we're passing to an argument explicitly
3715 // marked 'out'.
3716 bool ShouldCopy = true;
3717 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3718 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3719
3720 // If there was an lvalue adjustment, add it as a separate conversion.
3721 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3722 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3723 ImplicitConversionSequence LvalueICS;
3724 LvalueICS.setStandard();
3725 LvalueICS.Standard.setAsIdentityConversion();
3726 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3727 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003728 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003729 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003730
3731 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003732 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003733 DeclAccessPair dap;
3734 if (Initializer->getType() == Context.OverloadTy &&
3735 !S.ResolveAddressOfOverloadedFunction(Initializer
3736 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003737 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003738 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003739 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003740 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003741 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003742
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003743 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003744 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003745}
3746
3747InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003748 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 StepEnd = Steps.end();
3750 Step != StepEnd; ++Step)
3751 Step->Destroy();
3752}
3753
3754//===----------------------------------------------------------------------===//
3755// Perform initialization
3756//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003758getAssignmentAction(const InitializedEntity &Entity) {
3759 switch(Entity.getKind()) {
3760 case InitializedEntity::EK_Variable:
3761 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003762 case InitializedEntity::EK_Exception:
3763 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003764 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003765 return Sema::AA_Initializing;
3766
3767 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003768 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003769 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3770 return Sema::AA_Sending;
3771
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003772 return Sema::AA_Passing;
3773
3774 case InitializedEntity::EK_Result:
3775 return Sema::AA_Returning;
3776
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003777 case InitializedEntity::EK_Temporary:
3778 // FIXME: Can we tell apart casting vs. converting?
3779 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003781 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003782 case InitializedEntity::EK_ArrayElement:
3783 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003784 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003785 return Sema::AA_Initializing;
3786 }
3787
3788 return Sema::AA_Converting;
3789}
3790
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003791/// \brief Whether we should binding a created object as a temporary when
3792/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003793static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003794 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003795 case InitializedEntity::EK_ArrayElement:
3796 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003797 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003798 case InitializedEntity::EK_New:
3799 case InitializedEntity::EK_Variable:
3800 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003801 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003802 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003803 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003804 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003805 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003807 case InitializedEntity::EK_Parameter:
3808 case InitializedEntity::EK_Temporary:
3809 return true;
3810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003812 llvm_unreachable("missed an InitializedEntity kind?");
3813}
3814
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003815/// \brief Whether the given entity, when initialized with an object
3816/// created for that initialization, requires destruction.
3817static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3818 switch (Entity.getKind()) {
3819 case InitializedEntity::EK_Member:
3820 case InitializedEntity::EK_Result:
3821 case InitializedEntity::EK_New:
3822 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003823 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003824 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003825 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003826 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003828 case InitializedEntity::EK_Variable:
3829 case InitializedEntity::EK_Parameter:
3830 case InitializedEntity::EK_Temporary:
3831 case InitializedEntity::EK_ArrayElement:
3832 case InitializedEntity::EK_Exception:
3833 return true;
3834 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835
3836 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003837}
3838
Douglas Gregor523d46a2010-04-18 07:40:54 +00003839/// \brief Make a (potentially elidable) temporary copy of the object
3840/// provided by the given initializer by calling the appropriate copy
3841/// constructor.
3842///
3843/// \param S The Sema object used for type-checking.
3844///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003845/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003846/// the type of the initializer expression or a superclass thereof.
3847///
3848/// \param Enter The entity being initialized.
3849///
3850/// \param CurInit The initializer expression.
3851///
3852/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3853/// is permitted in C++03 (but not C++0x) when binding a reference to
3854/// an rvalue.
3855///
3856/// \returns An expression that copies the initializer expression into
3857/// a temporary object, or an error expression if a copy could not be
3858/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003859static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003860 QualType T,
3861 const InitializedEntity &Entity,
3862 ExprResult CurInit,
3863 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003864 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003865 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003867 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003868 Class = cast<CXXRecordDecl>(Record->getDecl());
3869 if (!Class)
3870 return move(CurInit);
3871
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003872 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003873 // When certain criteria are met, an implementation is allowed to
3874 // omit the copy/move construction of a class object, even if the
3875 // copy/move constructor and/or destructor for the object have
3876 // side effects. [...]
3877 // - when a temporary class object that has not been bound to a
3878 // reference (12.2) would be copied/moved to a class object
3879 // with the same cv-unqualified type, the copy/move operation
3880 // can be omitted by constructing the temporary object
3881 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003882 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003883 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003884 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003886 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003887 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003888 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003889 switch (Entity.getKind()) {
3890 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003891 Loc = Entity.getReturnLoc();
3892 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003893
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003894 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003895 Loc = Entity.getThrowLoc();
3896 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003898 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003899 Loc = Entity.getDecl()->getLocation();
3900 break;
3901
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003902 case InitializedEntity::EK_ArrayElement:
3903 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003904 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003905 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003906 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003907 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003908 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003909 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003910 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003911 Loc = CurInitExpr->getLocStart();
3912 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003913 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003914
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003915 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003916 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3917 return move(CurInit);
3918
Douglas Gregorcc15f012011-01-21 19:38:21 +00003919 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003920 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003921 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003922 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003923 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003924 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003925 // C++0x [dcl.init]p16, second bullet to class types, this
3926 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003927 CXXConstructorDecl *Constructor = 0;
3928
3929 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003930 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003931 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003932 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003933 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003934 continue;
3935
3936 DeclAccessPair FoundDecl
3937 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3938 S.AddOverloadCandidate(Constructor, FoundDecl,
3939 &CurInitExpr, 1, CandidateSet);
3940 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003941 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003942
3943 // Handle constructor templates.
3944 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3945 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003946 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003947
Douglas Gregor6493cc52010-11-08 17:16:59 +00003948 Constructor = cast<CXXConstructorDecl>(
3949 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003950 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003951 continue;
3952
3953 // FIXME: Do we need to limit this to copy-constructor-like
3954 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003955 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003956 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3957 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3958 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003959 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003960
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003961 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003962 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003963 case OR_Success:
3964 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003965
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003966 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003967 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3968 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3969 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003970 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003971 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003972 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003973 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003974 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003975 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003976
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003977 case OR_Ambiguous:
3978 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003979 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003980 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003981 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003982 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003984 case OR_Deleted:
3985 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003986 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003987 << CurInitExpr->getSourceRange();
3988 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00003989 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003990 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003991 }
3992
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003993 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003994 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003995 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003996
Anders Carlsson9a68a672010-04-21 18:47:17 +00003997 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003998 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003999
4000 if (IsExtraneousCopy) {
4001 // If this is a totally extraneous copy for C++03 reference
4002 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004003 // expression. We don't generate an (elided) copy operation here
4004 // because doing so would require us to pass down a flag to avoid
4005 // infinite recursion, where each step adds another extraneous,
4006 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004007
Douglas Gregor2559a702010-04-18 07:57:34 +00004008 // Instantiate the default arguments of any extra parameters in
4009 // the selected copy constructor, as if we were going to create a
4010 // proper call to the copy constructor.
4011 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4012 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4013 if (S.RequireCompleteType(Loc, Parm->getType(),
4014 S.PDiag(diag::err_call_incomplete_argument)))
4015 break;
4016
4017 // Build the default argument expression; we don't actually care
4018 // if this succeeds or not, because this routine will complain
4019 // if there was a problem.
4020 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4021 }
4022
Douglas Gregor523d46a2010-04-18 07:40:54 +00004023 return S.Owned(CurInitExpr);
4024 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004025
Chandler Carruth25ca4212011-02-25 19:41:05 +00004026 S.MarkDeclarationReferenced(Loc, Constructor);
4027
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004028 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004029 // constructor call (we might have derived-to-base conversions, or
4030 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004031 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004032 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004033 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004034
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004035 // Actually perform the constructor call.
4036 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004037 move_arg(ConstructorArgs),
4038 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004039 CXXConstructExpr::CK_Complete,
4040 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004041
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004042 // If we're supposed to bind temporaries, do so.
4043 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4044 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4045 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004046}
Douglas Gregor20093b42009-12-09 23:02:17 +00004047
Douglas Gregora41a8c52010-04-22 00:20:18 +00004048void InitializationSequence::PrintInitLocationNote(Sema &S,
4049 const InitializedEntity &Entity) {
4050 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4051 if (Entity.getDecl()->getLocation().isInvalid())
4052 return;
4053
4054 if (Entity.getDecl()->getDeclName())
4055 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4056 << Entity.getDecl()->getDeclName();
4057 else
4058 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4059 }
4060}
4061
Sebastian Redl3b802322011-07-14 19:07:55 +00004062static bool isReferenceBinding(const InitializationSequence::Step &s) {
4063 return s.Kind == InitializationSequence::SK_BindReference ||
4064 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4065}
4066
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004067ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004068InitializationSequence::Perform(Sema &S,
4069 const InitializedEntity &Entity,
4070 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004071 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004072 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004073 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004074 unsigned NumArgs = Args.size();
4075 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004076 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004078
Sebastian Redl7491c492011-06-05 13:59:11 +00004079 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004080 // If the declaration is a non-dependent, incomplete array type
4081 // that has an initializer, then its type will be completed once
4082 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004083 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004084 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004085 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004086 if (const IncompleteArrayType *ArrayT
4087 = S.Context.getAsIncompleteArrayType(DeclType)) {
4088 // FIXME: We don't currently have the ability to accurately
4089 // compute the length of an initializer list without
4090 // performing full type-checking of the initializer list
4091 // (since we have to determine where braces are implicitly
4092 // introduced and such). So, we fall back to making the array
4093 // type a dependently-sized array type with no specified
4094 // bound.
4095 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4096 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004097
Douglas Gregord87b61f2009-12-10 17:56:55 +00004098 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004099 if (DeclaratorDecl *DD = Entity.getDecl()) {
4100 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4101 TypeLoc TL = TInfo->getTypeLoc();
4102 if (IncompleteArrayTypeLoc *ArrayLoc
4103 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4104 Brackets = ArrayLoc->getBracketsRange();
4105 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004106 }
4107
4108 *ResultType
4109 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4110 /*NumElts=*/0,
4111 ArrayT->getSizeModifier(),
4112 ArrayT->getIndexTypeCVRQualifiers(),
4113 Brackets);
4114 }
4115
4116 }
4117 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004118 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4119 Kind.isExplicitCast());
4120 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004121 }
4122
Sebastian Redl7491c492011-06-05 13:59:11 +00004123 // No steps means no initialization.
4124 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004125 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004126
Douglas Gregord6542d82009-12-22 15:35:07 +00004127 QualType DestType = Entity.getType().getNonReferenceType();
4128 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004129 // the same as Entity.getDecl()->getType() in cases involving type merging,
4130 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004131 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004132 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004133 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004134
John McCall60d7b3a2010-08-24 06:29:42 +00004135 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004137 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004138 // grab the only argument out the Args and place it into the "current"
4139 // initializer.
4140 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004141 case SK_ResolveAddressOfOverloadedFunction:
4142 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004143 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004144 case SK_CastDerivedToBaseLValue:
4145 case SK_BindReference:
4146 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004147 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004148 case SK_UserConversion:
4149 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004150 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004151 case SK_QualificationConversionRValue:
4152 case SK_ConversionSequence:
4153 case SK_ListInitialization:
4154 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004155 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004156 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004157 case SK_ArrayInit:
4158 case SK_PassByIndirectCopyRestore:
4159 case SK_PassByIndirectRestore:
4160 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004161 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004162 CurInit = Args.get()[0];
4163 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004164
4165 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004166 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4167 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4168 if (CurInit.isInvalid())
4169 return ExprError();
4170 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004171 break;
John McCallf6a16482010-12-04 03:47:34 +00004172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004173
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004174 case SK_ConstructorInitialization:
4175 case SK_ZeroInitialization:
4176 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
4179 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004180 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004181 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004182 for (step_iterator Step = step_begin(), StepEnd = step_end();
4183 Step != StepEnd; ++Step) {
4184 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004185 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004186
John Wiegley429bb272011-04-08 18:41:53 +00004187 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004188
Douglas Gregor20093b42009-12-09 23:02:17 +00004189 switch (Step->Kind) {
4190 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004192 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004193 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004194 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004195 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004196 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004197 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004198 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004199
Douglas Gregor20093b42009-12-09 23:02:17 +00004200 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004201 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004202 case SK_CastDerivedToBaseLValue: {
4203 // We have a derived-to-base cast that produces either an rvalue or an
4204 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004205
John McCallf871d0c2010-08-07 06:22:56 +00004206 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004207
Douglas Gregor20093b42009-12-09 23:02:17 +00004208 // Casts to inaccessible base classes are allowed with C-style casts.
4209 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4210 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004211 CurInit.get()->getLocStart(),
4212 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004213 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004214 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004215
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004216 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4217 QualType T = SourceType;
4218 if (const PointerType *Pointer = T->getAs<PointerType>())
4219 T = Pointer->getPointeeType();
4220 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004221 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004222 cast<CXXRecordDecl>(RecordTy->getDecl()));
4223 }
4224
John McCall5baba9d2010-08-25 10:28:54 +00004225 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004226 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004227 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004228 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004229 VK_XValue :
4230 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004231 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4232 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004233 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004234 CurInit.get(),
4235 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004236 break;
4237 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004238
Douglas Gregor20093b42009-12-09 23:02:17 +00004239 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004240 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004241 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4242 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004243 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004244 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004245 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004246 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004247 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004248 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004249
John Wiegley429bb272011-04-08 18:41:53 +00004250 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004251 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004252 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4253 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004254 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004255 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004256 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258
Douglas Gregor20093b42009-12-09 23:02:17 +00004259 // Reference binding does not have any corresponding ASTs.
4260
4261 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004262 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004263 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004264
Douglas Gregor20093b42009-12-09 23:02:17 +00004265 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004266
Douglas Gregor20093b42009-12-09 23:02:17 +00004267 case SK_BindReferenceToTemporary:
4268 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004269 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004270 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004271
Douglas Gregor03e80032011-06-21 17:03:29 +00004272 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004273 CurInit = new (S.Context) MaterializeTemporaryExpr(
4274 Entity.getType().getNonReferenceType(),
4275 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004276 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004277
4278 // If we're binding to an Objective-C object that has lifetime, we
4279 // need cleanups.
4280 if (S.getLangOptions().ObjCAutoRefCount &&
4281 CurInit.get()->getType()->isObjCLifetimeType())
4282 S.ExprNeedsCleanups = true;
4283
Douglas Gregor20093b42009-12-09 23:02:17 +00004284 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285
Douglas Gregor523d46a2010-04-18 07:40:54 +00004286 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004288 /*IsExtraneousCopy=*/true);
4289 break;
4290
Douglas Gregor20093b42009-12-09 23:02:17 +00004291 case SK_UserConversion: {
4292 // We have a user-defined conversion that invokes either a constructor
4293 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004294 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004295 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004296 FunctionDecl *Fn = Step->Function.Function;
4297 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004298 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004299 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004300 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004301 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004302 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004303 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004304 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004305
Douglas Gregor20093b42009-12-09 23:02:17 +00004306 // Determine the arguments required to actually perform the constructor
4307 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004308 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004309 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004310 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004311 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004312 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313
Douglas Gregor20093b42009-12-09 23:02:17 +00004314 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004316 move_arg(ConstructorArgs),
4317 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004318 CXXConstructExpr::CK_Complete,
4319 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004320 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004321 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004322
Anders Carlsson9a68a672010-04-21 18:47:17 +00004323 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004324 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004325 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326
John McCall2de56d12010-08-25 11:45:40 +00004327 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004328 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4329 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4330 S.IsDerivedFrom(SourceType, Class))
4331 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004333 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004334 } else {
4335 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004336 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004337 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004338 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004339 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004340 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004341
4342 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004343 // derived-to-base conversion? I believe the answer is "no", because
4344 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004345 ExprResult CurInitExprRes =
4346 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4347 FoundFn, Conversion);
4348 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004349 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004350 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004351
Douglas Gregor20093b42009-12-09 23:02:17 +00004352 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004353 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004354 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004355 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004356
John McCall2de56d12010-08-25 11:45:40 +00004357 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004359 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004360 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004361
Sebastian Redl3b802322011-07-14 19:07:55 +00004362 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004363 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004364 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004365 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004366 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004367 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004368 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004369 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004370 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004371 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004372 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4373 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004374 }
4375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004376
Sebastian Redl906082e2010-07-20 04:20:21 +00004377 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004378 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004379 CurInit.get()->getType(),
4380 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004381 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004382
Douglas Gregor2f599792010-04-02 18:24:57 +00004383 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004384 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4385 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004386
Douglas Gregor20093b42009-12-09 23:02:17 +00004387 break;
4388 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004389
Douglas Gregor20093b42009-12-09 23:02:17 +00004390 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004391 case SK_QualificationConversionXValue:
4392 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004393 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004394 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004395 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004396 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004397 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004398 VK_XValue :
4399 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004400 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004401 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004402 }
4403
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004404 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004405 Sema::CheckedConversionKind CCK
4406 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4407 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4408 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4409 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004410 ExprResult CurInitExprRes =
4411 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004412 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004413 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004414 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004415 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004416 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004418
Douglas Gregord87b61f2009-12-10 17:56:55 +00004419 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004420 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004421 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00004422 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00004423 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004424
4425 CurInit.release();
4426 CurInit = S.Owned(InitList);
4427 break;
4428 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004429
4430 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004431 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004432 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004433 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434
Douglas Gregor51c56d62009-12-14 20:49:26 +00004435 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004436 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004437 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4438 ? Kind.getEqualLoc()
4439 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004440
4441 if (Kind.getKind() == InitializationKind::IK_Default) {
4442 // Force even a trivial, implicit default constructor to be
4443 // semantically checked. We do this explicitly because we don't build
4444 // the definition for completely trivial constructors.
4445 CXXRecordDecl *ClassDecl = Constructor->getParent();
4446 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004447 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004448 ClassDecl->hasTrivialDefaultConstructor() &&
4449 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004450 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4451 }
4452
Douglas Gregor51c56d62009-12-14 20:49:26 +00004453 // Determine the arguments required to actually perform the constructor
4454 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004456 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004457 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458
4459
Douglas Gregor91be6f52010-03-02 17:18:33 +00004460 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004461 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004462 (Kind.getKind() == InitializationKind::IK_Direct ||
4463 Kind.getKind() == InitializationKind::IK_Value)) {
4464 // An explicitly-constructed temporary, e.g., X(1, 2).
4465 unsigned NumExprs = ConstructorArgs.size();
4466 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004467 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004468 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004469
Douglas Gregorab6677e2010-09-08 00:15:04 +00004470 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4471 if (!TSInfo)
4472 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004473
Douglas Gregor91be6f52010-03-02 17:18:33 +00004474 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4475 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004476 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004477 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004478 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004479 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004480 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004481 } else {
4482 CXXConstructExpr::ConstructionKind ConstructKind =
4483 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004485 if (Entity.getKind() == InitializedEntity::EK_Base) {
4486 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004488 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004489 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004490 ConstructKind = CXXConstructExpr::CK_Delegating;
4491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Chandler Carruth428edaf2010-10-25 08:47:36 +00004493 // Only get the parenthesis range if it is a direct construction.
4494 SourceRange parenRange =
4495 Kind.getKind() == InitializationKind::IK_Direct ?
4496 Kind.getParenRange() : SourceRange();
4497
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004498 // If the entity allows NRVO, mark the construction as elidable
4499 // unconditionally.
4500 if (Entity.allowsNRVO())
4501 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4502 Constructor, /*Elidable=*/true,
4503 move_arg(ConstructorArgs),
4504 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004505 ConstructKind,
4506 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004507 else
4508 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004509 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004510 move_arg(ConstructorArgs),
4511 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004512 ConstructKind,
4513 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004514 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004515 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004516 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004517
4518 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004519 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004520 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004521 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522
Douglas Gregor2f599792010-04-02 18:24:57 +00004523 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004524 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525
Douglas Gregor51c56d62009-12-14 20:49:26 +00004526 break;
4527 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004528
Douglas Gregor71d17402009-12-15 00:01:57 +00004529 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004530 step_iterator NextStep = Step;
4531 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004532 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004533 NextStep->Kind == SK_ConstructorInitialization) {
4534 // The need for zero-initialization is recorded directly into
4535 // the call to the object's constructor within the next step.
4536 ConstructorInitRequiresZeroInit = true;
4537 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4538 S.getLangOptions().CPlusPlus &&
4539 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004540 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4541 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004542 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004543 Kind.getRange().getBegin());
4544
4545 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4546 TSInfo->getType().getNonLValueExprType(S.Context),
4547 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004548 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004549 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004550 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004551 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004552 break;
4553 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004554
4555 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004556 QualType SourceType = CurInit.get()->getType();
4557 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004558 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004559 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4560 if (Result.isInvalid())
4561 return ExprError();
4562 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004563
4564 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004565 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004566 if (ConvTy != Sema::Compatible &&
4567 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004568 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004569 == Sema::Compatible)
4570 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004571 if (CurInitExprRes.isInvalid())
4572 return ExprError();
4573 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004574
Douglas Gregora41a8c52010-04-22 00:20:18 +00004575 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004576 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4577 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004578 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004579 getAssignmentAction(Entity),
4580 &Complained)) {
4581 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004582 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004583 } else if (Complained)
4584 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004585 break;
4586 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004587
4588 case SK_StringInit: {
4589 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004590 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004591 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004592 break;
4593 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004594
4595 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004596 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004597 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004598 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004599 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004600
4601 case SK_ArrayInit:
4602 // Okay: we checked everything before creating this step. Note that
4603 // this is a GNU extension.
4604 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004605 << Step->Type << CurInit.get()->getType()
4606 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004607
4608 // If the destination type is an incomplete array type, update the
4609 // type accordingly.
4610 if (ResultType) {
4611 if (const IncompleteArrayType *IncompleteDest
4612 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4613 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004614 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004615 *ResultType = S.Context.getConstantArrayType(
4616 IncompleteDest->getElementType(),
4617 ConstantSource->getSize(),
4618 ArrayType::Normal, 0);
4619 }
4620 }
4621 }
John McCallf85e1932011-06-15 23:02:42 +00004622 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004623
John McCallf85e1932011-06-15 23:02:42 +00004624 case SK_PassByIndirectCopyRestore:
4625 case SK_PassByIndirectRestore:
4626 checkIndirectCopyRestoreSource(S, CurInit.get());
4627 CurInit = S.Owned(new (S.Context)
4628 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4629 Step->Kind == SK_PassByIndirectCopyRestore));
4630 break;
4631
4632 case SK_ProduceObjCObject:
4633 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4634 CK_ObjCProduceObject,
4635 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004636 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004637 }
4638 }
John McCall15d7d122010-11-11 03:21:53 +00004639
4640 // Diagnose non-fatal problems with the completed initialization.
4641 if (Entity.getKind() == InitializedEntity::EK_Member &&
4642 cast<FieldDecl>(Entity.getDecl())->isBitField())
4643 S.CheckBitFieldInitialization(Kind.getLocation(),
4644 cast<FieldDecl>(Entity.getDecl()),
4645 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004646
Douglas Gregor20093b42009-12-09 23:02:17 +00004647 return move(CurInit);
4648}
4649
4650//===----------------------------------------------------------------------===//
4651// Diagnose initialization failures
4652//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004654 const InitializedEntity &Entity,
4655 const InitializationKind &Kind,
4656 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004657 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004658 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
Douglas Gregord6542d82009-12-22 15:35:07 +00004660 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004661 switch (Failure) {
4662 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004663 // FIXME: Customize for the initialized entity?
4664 if (NumArgs == 0)
4665 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4666 << DestType.getNonReferenceType();
4667 else // FIXME: diagnostic below could be better!
4668 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4669 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004670 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004671
Douglas Gregor20093b42009-12-09 23:02:17 +00004672 case FK_ArrayNeedsInitList:
4673 case FK_ArrayNeedsInitListOrStringLiteral:
4674 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4675 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4676 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004678 case FK_ArrayTypeMismatch:
4679 case FK_NonConstantArrayInit:
4680 S.Diag(Kind.getLocation(),
4681 (Failure == FK_ArrayTypeMismatch
4682 ? diag::err_array_init_different_type
4683 : diag::err_array_init_non_constant_array))
4684 << DestType.getNonReferenceType()
4685 << Args[0]->getType()
4686 << Args[0]->getSourceRange();
4687 break;
4688
John McCall6bb80172010-03-30 21:47:33 +00004689 case FK_AddressOfOverloadFailed: {
4690 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004691 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004692 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004693 true,
4694 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004695 break;
John McCall6bb80172010-03-30 21:47:33 +00004696 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004697
Douglas Gregor20093b42009-12-09 23:02:17 +00004698 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004699 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004700 switch (FailedOverloadResult) {
4701 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004702 if (Failure == FK_UserConversionOverloadFailed)
4703 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4704 << Args[0]->getType() << DestType
4705 << Args[0]->getSourceRange();
4706 else
4707 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4708 << DestType << Args[0]->getType()
4709 << Args[0]->getSourceRange();
4710
John McCall120d63c2010-08-24 20:38:10 +00004711 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004712 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004713
Douglas Gregor20093b42009-12-09 23:02:17 +00004714 case OR_No_Viable_Function:
4715 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4716 << Args[0]->getType() << DestType.getNonReferenceType()
4717 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004718 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004719 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720
Douglas Gregor20093b42009-12-09 23:02:17 +00004721 case OR_Deleted: {
4722 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4723 << Args[0]->getType() << DestType.getNonReferenceType()
4724 << Args[0]->getSourceRange();
4725 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004726 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004727 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4728 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004729 if (Ovl == OR_Deleted) {
4730 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004731 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004732 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004733 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004734 }
4735 break;
4736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004737
Douglas Gregor20093b42009-12-09 23:02:17 +00004738 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004739 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004740 break;
4741 }
4742 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004743
Douglas Gregor20093b42009-12-09 23:02:17 +00004744 case FK_NonConstLValueReferenceBindingToTemporary:
4745 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004746 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004747 Failure == FK_NonConstLValueReferenceBindingToTemporary
4748 ? diag::err_lvalue_reference_bind_to_temporary
4749 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004750 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004751 << DestType.getNonReferenceType()
4752 << Args[0]->getType()
4753 << Args[0]->getSourceRange();
4754 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004755
Douglas Gregor20093b42009-12-09 23:02:17 +00004756 case FK_RValueReferenceBindingToLValue:
4757 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004758 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004759 << Args[0]->getSourceRange();
4760 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004761
Douglas Gregor20093b42009-12-09 23:02:17 +00004762 case FK_ReferenceInitDropsQualifiers:
4763 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4764 << DestType.getNonReferenceType()
4765 << Args[0]->getType()
4766 << Args[0]->getSourceRange();
4767 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004768
Douglas Gregor20093b42009-12-09 23:02:17 +00004769 case FK_ReferenceInitFailed:
4770 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4771 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004772 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004773 << Args[0]->getType()
4774 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004775 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4776 Args[0]->getType()->isObjCObjectPointerType())
4777 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004778 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004779
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004780 case FK_ConversionFailed: {
4781 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004782 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4783 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004784 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004785 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004786 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004787 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004788 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4789 Args[0]->getType()->isObjCObjectPointerType())
4790 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004791 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004792 }
John Wiegley429bb272011-04-08 18:41:53 +00004793
4794 case FK_ConversionFromPropertyFailed:
4795 // No-op. This error has already been reported.
4796 break;
4797
Douglas Gregord87b61f2009-12-10 17:56:55 +00004798 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004799 SourceRange R;
4800
4801 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004802 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004803 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004804 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004805 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004806
Douglas Gregor19311e72010-09-08 21:40:08 +00004807 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4808 if (Kind.isCStyleOrFunctionalCast())
4809 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4810 << R;
4811 else
4812 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4813 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004814 break;
4815 }
4816
4817 case FK_ReferenceBindingToInitList:
4818 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4819 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4820 break;
4821
4822 case FK_InitListBadDestinationType:
4823 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4824 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4825 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826
Douglas Gregor51c56d62009-12-14 20:49:26 +00004827 case FK_ConstructorOverloadFailed: {
4828 SourceRange ArgsRange;
4829 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004830 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004831 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004832
Douglas Gregor51c56d62009-12-14 20:49:26 +00004833 // FIXME: Using "DestType" for the entity we're printing is probably
4834 // bad.
4835 switch (FailedOverloadResult) {
4836 case OR_Ambiguous:
4837 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4838 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004839 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4840 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004841 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004842
Douglas Gregor51c56d62009-12-14 20:49:26 +00004843 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004844 if (Kind.getKind() == InitializationKind::IK_Default &&
4845 (Entity.getKind() == InitializedEntity::EK_Base ||
4846 Entity.getKind() == InitializedEntity::EK_Member) &&
4847 isa<CXXConstructorDecl>(S.CurContext)) {
4848 // This is implicit default initialization of a member or
4849 // base within a constructor. If no viable function was
4850 // found, notify the user that she needs to explicitly
4851 // initialize this base/member.
4852 CXXConstructorDecl *Constructor
4853 = cast<CXXConstructorDecl>(S.CurContext);
4854 if (Entity.getKind() == InitializedEntity::EK_Base) {
4855 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4856 << Constructor->isImplicit()
4857 << S.Context.getTypeDeclType(Constructor->getParent())
4858 << /*base=*/0
4859 << Entity.getType();
4860
4861 RecordDecl *BaseDecl
4862 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4863 ->getDecl();
4864 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4865 << S.Context.getTagDeclType(BaseDecl);
4866 } else {
4867 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4868 << Constructor->isImplicit()
4869 << S.Context.getTypeDeclType(Constructor->getParent())
4870 << /*member=*/1
4871 << Entity.getName();
4872 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4873
4874 if (const RecordType *Record
4875 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004876 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004877 diag::note_previous_decl)
4878 << S.Context.getTagDeclType(Record->getDecl());
4879 }
4880 break;
4881 }
4882
Douglas Gregor51c56d62009-12-14 20:49:26 +00004883 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4884 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004885 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004886 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004887
Douglas Gregor51c56d62009-12-14 20:49:26 +00004888 case OR_Deleted: {
4889 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4890 << true << DestType << ArgsRange;
4891 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004892 OverloadingResult Ovl
4893 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004894 if (Ovl == OR_Deleted) {
4895 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004896 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004897 } else {
4898 llvm_unreachable("Inconsistent overload resolution?");
4899 }
4900 break;
4901 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004902
Douglas Gregor51c56d62009-12-14 20:49:26 +00004903 case OR_Success:
4904 llvm_unreachable("Conversion did not fail!");
4905 break;
4906 }
4907 break;
4908 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004909
Douglas Gregor99a2e602009-12-16 01:38:02 +00004910 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004911 if (Entity.getKind() == InitializedEntity::EK_Member &&
4912 isa<CXXConstructorDecl>(S.CurContext)) {
4913 // This is implicit default-initialization of a const member in
4914 // a constructor. Complain that it needs to be explicitly
4915 // initialized.
4916 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4917 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4918 << Constructor->isImplicit()
4919 << S.Context.getTypeDeclType(Constructor->getParent())
4920 << /*const=*/1
4921 << Entity.getName();
4922 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4923 << Entity.getName();
4924 } else {
4925 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4926 << DestType << (bool)DestType->getAs<RecordType>();
4927 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004928 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004929
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004930 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004931 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004932 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004933 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004935
Douglas Gregora41a8c52010-04-22 00:20:18 +00004936 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004937 return true;
4938}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004939
Chris Lattner5f9e2722011-07-23 10:55:15 +00004940void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004941 switch (SequenceKind) {
4942 case FailedSequence: {
4943 OS << "Failed sequence: ";
4944 switch (Failure) {
4945 case FK_TooManyInitsForReference:
4946 OS << "too many initializers for reference";
4947 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004948
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004949 case FK_ArrayNeedsInitList:
4950 OS << "array requires initializer list";
4951 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004952
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004953 case FK_ArrayNeedsInitListOrStringLiteral:
4954 OS << "array requires initializer list or string literal";
4955 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004956
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004957 case FK_ArrayTypeMismatch:
4958 OS << "array type mismatch";
4959 break;
4960
4961 case FK_NonConstantArrayInit:
4962 OS << "non-constant array initializer";
4963 break;
4964
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004965 case FK_AddressOfOverloadFailed:
4966 OS << "address of overloaded function failed";
4967 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004968
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004969 case FK_ReferenceInitOverloadFailed:
4970 OS << "overload resolution for reference initialization failed";
4971 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004972
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004973 case FK_NonConstLValueReferenceBindingToTemporary:
4974 OS << "non-const lvalue reference bound to temporary";
4975 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004976
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004977 case FK_NonConstLValueReferenceBindingToUnrelated:
4978 OS << "non-const lvalue reference bound to unrelated type";
4979 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004980
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004981 case FK_RValueReferenceBindingToLValue:
4982 OS << "rvalue reference bound to an lvalue";
4983 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004984
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004985 case FK_ReferenceInitDropsQualifiers:
4986 OS << "reference initialization drops qualifiers";
4987 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004988
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004989 case FK_ReferenceInitFailed:
4990 OS << "reference initialization failed";
4991 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004992
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004993 case FK_ConversionFailed:
4994 OS << "conversion failed";
4995 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996
John Wiegley429bb272011-04-08 18:41:53 +00004997 case FK_ConversionFromPropertyFailed:
4998 OS << "conversion from property failed";
4999 break;
5000
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005001 case FK_TooManyInitsForScalar:
5002 OS << "too many initializers for scalar";
5003 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005004
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005005 case FK_ReferenceBindingToInitList:
5006 OS << "referencing binding to initializer list";
5007 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005008
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005009 case FK_InitListBadDestinationType:
5010 OS << "initializer list for non-aggregate, non-scalar type";
5011 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005012
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005013 case FK_UserConversionOverloadFailed:
5014 OS << "overloading failed for user-defined conversion";
5015 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005016
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005017 case FK_ConstructorOverloadFailed:
5018 OS << "constructor overloading failed";
5019 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005020
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005021 case FK_DefaultInitOfConst:
5022 OS << "default initialization of a const variable";
5023 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005024
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005025 case FK_Incomplete:
5026 OS << "initialization of incomplete type";
5027 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005028 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005029 OS << '\n';
5030 return;
5031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005032
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005033 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005034 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005035 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005036
Sebastian Redl7491c492011-06-05 13:59:11 +00005037 case NormalSequence:
5038 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005039 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005040 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005041
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005042 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5043 if (S != step_begin()) {
5044 OS << " -> ";
5045 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005046
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005047 switch (S->Kind) {
5048 case SK_ResolveAddressOfOverloadedFunction:
5049 OS << "resolve address of overloaded function";
5050 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005051
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005052 case SK_CastDerivedToBaseRValue:
5053 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5054 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005055
Sebastian Redl906082e2010-07-20 04:20:21 +00005056 case SK_CastDerivedToBaseXValue:
5057 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5058 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005059
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005060 case SK_CastDerivedToBaseLValue:
5061 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5062 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005063
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005064 case SK_BindReference:
5065 OS << "bind reference to lvalue";
5066 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005068 case SK_BindReferenceToTemporary:
5069 OS << "bind reference to a temporary";
5070 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005071
Douglas Gregor523d46a2010-04-18 07:40:54 +00005072 case SK_ExtraneousCopyToTemporary:
5073 OS << "extraneous C++03 copy to temporary";
5074 break;
5075
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005076 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005077 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005078 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005079
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005080 case SK_QualificationConversionRValue:
5081 OS << "qualification conversion (rvalue)";
5082
Sebastian Redl906082e2010-07-20 04:20:21 +00005083 case SK_QualificationConversionXValue:
5084 OS << "qualification conversion (xvalue)";
5085
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005086 case SK_QualificationConversionLValue:
5087 OS << "qualification conversion (lvalue)";
5088 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005090 case SK_ConversionSequence:
5091 OS << "implicit conversion sequence (";
5092 S->ICS->DebugPrint(); // FIXME: use OS
5093 OS << ")";
5094 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005095
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005096 case SK_ListInitialization:
5097 OS << "list initialization";
5098 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005099
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005100 case SK_ConstructorInitialization:
5101 OS << "constructor initialization";
5102 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005103
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005104 case SK_ZeroInitialization:
5105 OS << "zero initialization";
5106 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005107
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005108 case SK_CAssignment:
5109 OS << "C assignment";
5110 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005111
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005112 case SK_StringInit:
5113 OS << "string initialization";
5114 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005115
5116 case SK_ObjCObjectConversion:
5117 OS << "Objective-C object conversion";
5118 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005119
5120 case SK_ArrayInit:
5121 OS << "array initialization";
5122 break;
John McCallf85e1932011-06-15 23:02:42 +00005123
5124 case SK_PassByIndirectCopyRestore:
5125 OS << "pass by indirect copy and restore";
5126 break;
5127
5128 case SK_PassByIndirectRestore:
5129 OS << "pass by indirect restore";
5130 break;
5131
5132 case SK_ProduceObjCObject:
5133 OS << "Objective-C object retension";
5134 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005135 }
5136 }
5137}
5138
5139void InitializationSequence::dump() const {
5140 dump(llvm::errs());
5141}
5142
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005143static void DiagnoseNarrowingInInitList(
5144 Sema& S, QualType EntityType, const Expr *InitE,
5145 bool Constant, const APValue &ConstantValue) {
5146 if (Constant) {
5147 S.Diag(InitE->getLocStart(),
5148 S.getLangOptions().CPlusPlus0x
5149 ? diag::err_init_list_constant_narrowing
5150 : diag::warn_init_list_constant_narrowing)
5151 << InitE->getSourceRange()
5152 << ConstantValue
5153 << EntityType;
5154 } else
5155 S.Diag(InitE->getLocStart(),
5156 S.getLangOptions().CPlusPlus0x
5157 ? diag::err_init_list_variable_narrowing
5158 : diag::warn_init_list_variable_narrowing)
5159 << InitE->getSourceRange()
5160 << InitE->getType()
5161 << EntityType;
5162
5163 llvm::SmallString<128> StaticCast;
5164 llvm::raw_svector_ostream OS(StaticCast);
5165 OS << "static_cast<";
5166 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5167 // It's important to use the typedef's name if there is one so that the
5168 // fixit doesn't break code using types like int64_t.
5169 //
5170 // FIXME: This will break if the typedef requires qualification. But
5171 // getQualifiedNameAsString() includes non-machine-parsable components.
5172 OS << TT->getDecl();
5173 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5174 OS << BT->getName(S.getLangOptions());
5175 else {
5176 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5177 // with a broken cast.
5178 return;
5179 }
5180 OS << ">(";
5181 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5182 << InitE->getSourceRange()
5183 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5184 << FixItHint::CreateInsertion(
5185 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5186}
5187
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005188//===----------------------------------------------------------------------===//
5189// Initialization helper functions
5190//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005191bool
5192Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5193 ExprResult Init) {
5194 if (Init.isInvalid())
5195 return false;
5196
5197 Expr *InitE = Init.get();
5198 assert(InitE && "No initialization expression");
5199
5200 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5201 SourceLocation());
5202 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005203 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005204}
5205
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005206ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005207Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5208 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005209 ExprResult Init,
5210 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005211 if (Init.isInvalid())
5212 return ExprError();
5213
John McCall15d7d122010-11-11 03:21:53 +00005214 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005215 assert(InitE && "No initialization expression?");
5216
5217 if (EqualLoc.isInvalid())
5218 EqualLoc = InitE->getLocStart();
5219
5220 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5221 EqualLoc);
5222 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5223 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005224
5225 bool Constant = false;
5226 APValue Result;
5227 if (TopLevelOfInitList &&
5228 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5229 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5230 Constant, Result);
5231 }
John McCallf312b1e2010-08-26 23:41:50 +00005232 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005233}