blob: 7c27e6fbae08024b0f14a7a820a9cf27237a7bdb [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//
Sebastian Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000026#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000027using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000028
Chris Lattnerdd8e0062009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCallce6c9b72011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattner8879e3b2009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // Handle @encode, which is a narrow string.
42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
43 return Init;
44
45 // Otherwise we can only handle string literals.
46 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000050
51 switch (SL->getKind()) {
52 case StringLiteral::Ascii:
53 case StringLiteral::UTF8:
54 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000057 case StringLiteral::UTF16:
58 return ElemTy->isChar16Type() ? Init : 0;
59 case StringLiteral::UTF32:
60 return ElemTy->isChar32Type() ? Init : 0;
61 case StringLiteral::Wide:
62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63 // correction from DR343): "An array with element type compatible with a
64 // qualified or unqualified version of wchar_t may be initialized by a wide
65 // string literal, optionally enclosed in braces."
66 if (Context.typesAreCompatible(Context.getWCharType(),
67 ElemTy.getUnqualifiedType()))
68 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000069
Douglas Gregor5cee1192011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor5cee1192011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074}
75
John McCallce6c9b72011-02-21 07:22:22 +000076static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77 const ArrayType *arrayType = Context.getAsArrayType(declType);
78 if (!arrayType) return 0;
79
80 return IsStringInit(init, arrayType, Context);
81}
82
John McCallfef8b342011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000085 // Get the length of the string as parsed.
86 uint64_t StrLength =
87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
88
Mike Stump1eb44332009-09-09 15:08:12 +000089
Chris Lattnerdd8e0062009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000099 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000100 }
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Eli Friedman8718a6a2009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000105 // the size may be smaller or larger than the string we are initializing.
106 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109 // For Pascal strings it's OK to strip off the terminating null character,
110 // so the example below is valid:
111 //
112 // unsigned char a[2] = "\pa";
113 if (SL->isPascal())
114 StrLength--;
115 }
116
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000117 // [dcl.init.string]p2
118 if (StrLength > CAT->getSize().getZExtValue())
119 S.Diag(Str->getSourceRange().getBegin(),
120 diag::err_initializer_string_for_char_array_too_long)
121 << Str->getSourceRange();
122 } else {
123 // C99 6.7.8p14.
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
128 }
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregor9e80f722009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000168namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000177 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000185 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000186 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000187 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000193 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000197 void CheckComplexType(const InitializedEntity &Entity,
198 InitListExpr *IList, QualType DeclType,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000203 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000207 void CheckReferenceType(const InitializedEntity &Entity,
208 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000209 unsigned &Index,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000212 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000213 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000216 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000217 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000220 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000221 unsigned &StructuredIndex,
222 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000223 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000224 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000225 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000229 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000230 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000231 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 RecordDecl::field_iterator *NextField,
234 llvm::APSInt *NextElementIndex,
235 unsigned &Index,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000238 bool FinishSubobjectInit,
239 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
241 QualType CurrentObjectType,
242 InitListExpr *StructuredList,
243 unsigned StructuredIndex,
244 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000245 void UpdateStructuredListElement(InitListExpr *StructuredList,
246 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 Expr *expr);
248 int numArrayElements(QualType DeclType);
249 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000250
Douglas Gregord6d37de2009-12-22 00:05:34 +0000251 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
253 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000254 void FillInValueInitializations(const InitializedEntity &Entity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000256 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257 Expr *InitExpr, FieldDecl *Field,
258 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000259public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000260 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000261 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 bool HadError() { return hadError; }
263
264 // @brief Retrieves the fully-structured initializer list used for
265 // semantic analysis and code generation.
266 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
267};
Chris Lattner8b419b92009-02-24 22:48:58 +0000268} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000269
Douglas Gregord6d37de2009-12-22 00:05:34 +0000270void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
271 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000273 bool &RequiresSecondPass) {
274 SourceLocation Loc = ILE->getSourceRange().getBegin();
275 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000277 = InitializedEntity::InitializeMember(Field, &ParentEntity);
278 if (Init >= NumInits || !ILE->getInit(Init)) {
279 // FIXME: We probably don't need to handle references
280 // specially here, since value-initialization of references is
281 // handled in InitializationSequence.
282 if (Field->getType()->isReferenceType()) {
283 // C++ [dcl.init.aggr]p9:
284 // If an incomplete or empty initializer-list leaves a
285 // member of reference type uninitialized, the program is
286 // ill-formed.
287 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
288 << Field->getType()
289 << ILE->getSyntacticForm()->getSourceRange();
290 SemaRef.Diag(Field->getLocation(),
291 diag::note_uninit_reference_member);
292 hadError = true;
293 return;
294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000295
Douglas Gregord6d37de2009-12-22 00:05:34 +0000296 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
297 true);
298 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
299 if (!InitSeq) {
300 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
301 hadError = true;
302 return;
303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000304
John McCall60d7b3a2010-08-24 06:29:42 +0000305 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000306 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000307 if (MemberInit.isInvalid()) {
308 hadError = true;
309 return;
310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000311
Douglas Gregord6d37de2009-12-22 00:05:34 +0000312 if (hadError) {
313 // Do nothing
314 } else if (Init < NumInits) {
315 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000316 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000317 // Value-initialization requires a constructor call, so
318 // extend the initializer list to include the constructor
319 // call and make a note that we'll need to take another pass
320 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000321 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322 RequiresSecondPass = true;
323 }
324 } else if (InitListExpr *InnerILE
325 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000326 FillInValueInitializations(MemberEntity, InnerILE,
327 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328}
329
Douglas Gregor4c678342009-01-28 21:54:33 +0000330/// Recursively replaces NULL values within the given initializer list
331/// with expressions that perform value-initialization of the
332/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000334InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
335 InitListExpr *ILE,
336 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Ted Kremenek6217b802009-07-29 21:53:49 +0000343 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344 if (RType->getDecl()->isUnion() &&
345 ILE->getInitializedFieldInUnion())
346 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347 Entity, ILE, RequiresSecondPass);
348 else {
349 unsigned Init = 0;
350 for (RecordDecl::field_iterator
351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
355 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000356
Douglas Gregord6d37de2009-12-22 00:05:34 +0000357 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000359
360 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
361 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000362 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000363
Douglas Gregord6d37de2009-12-22 00:05:34 +0000364 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365
Douglas Gregord6d37de2009-12-22 00:05:34 +0000366 // Only look at the first initialization of a union.
367 if (RType->getDecl()->isUnion())
368 break;
369 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000370 }
371
372 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000373 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000374
375 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000377 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 unsigned NumInits = ILE->getNumInits();
379 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000380 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000385 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000386 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000389 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000390 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000392 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000396 if (hadError)
397 return;
398
Anders Carlssond3d824d2010-01-23 04:34:47 +0000399 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401 ElementEntity.setElementIndex(Init);
402
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
405 true);
406 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
407 if (!InitSeq) {
408 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000409 hadError = true;
410 return;
411 }
412
John McCall60d7b3a2010-08-24 06:29:42 +0000413 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000414 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000416 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 return;
418 }
419
420 if (hadError) {
421 // Do nothing
422 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000423 // For arrays, just set the expression used for value-initialization
424 // of the "holes" in the array.
425 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
426 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
427 else
428 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000429 } else {
430 // For arrays, just set the expression used for value-initialization
431 // of the rest of elements and exit.
432 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
433 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
434 return;
435 }
436
Sebastian Redl7491c492011-06-05 13:59:11 +0000437 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000438 // Value-initialization requires a constructor call, so
439 // extend the initializer list to include the constructor
440 // call and make a note that we'll need to take another pass
441 // through the initializer list.
442 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
443 RequiresSecondPass = true;
444 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000445 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000446 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
448 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000449 }
450}
451
Chris Lattner68355a52009-01-29 05:10:57 +0000452
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000453InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000454 InitListExpr *IL, QualType &T,
455 bool VerifyOnly)
456 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000458
Eli Friedmanb85f7072008-05-19 19:16:24 +0000459 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000460 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000461 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000462 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000464 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000465 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000466
Sebastian Redl14b0c192011-09-24 17:48:00 +0000467 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000470 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000471 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000472 RequiresSecondPass);
473 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000474}
475
476int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000479 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000481 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
482 }
483 return maxElements;
484}
485
486int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000488 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000489 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 Field != FieldEnd; ++Field) {
493 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494 ++InitializableMembers;
495 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000496 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000499}
500
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000501void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000502 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 QualType T, unsigned &Index,
504 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000505 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Steve Naroff0cca7492008-05-01 22:18:59 +0000508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000510 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000511 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000512 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000513 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000514 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000515 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000516
Eli Friedman402256f2008-05-25 13:49:22 +0000517 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000518 if (!VerifyOnly)
519 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
520 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000522 hadError = true;
523 return;
524 }
525
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 // Build a structured initializer list corresponding to this subobject.
527 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000528 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
529 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000530 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
531 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000532 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000533
Douglas Gregor4c678342009-01-28 21:54:33 +0000534 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000535 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000537 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000538 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000539 StructuredSubobjectInitIndex);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000540 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000541 if (!VerifyOnly) {
542 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000543
Sebastian Redl14b0c192011-09-24 17:48:00 +0000544 // Update the structured sub-object initializer so that it's ending
545 // range corresponds with the end of the last initializer it used.
546 if (EndIndex < ParentIList->getNumInits()) {
547 SourceLocation EndLoc
548 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
549 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551
Sebastian Redl14b0c192011-09-24 17:48:00 +0000552 // Warn about missing braces.
553 if (T->isArrayType() || T->isRecordType()) {
554 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
555 diag::warn_missing_braces)
556 << StructuredSubobjectInitList->getSourceRange()
557 << FixItHint::CreateInsertion(
558 StructuredSubobjectInitList->getLocStart(), "{")
559 << FixItHint::CreateInsertion(
560 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000562 "}");
563 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000564 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000565}
566
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000567void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 unsigned &Index,
570 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000571 unsigned &StructuredIndex,
572 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000573 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000574 if (!VerifyOnly) {
575 SyntacticToSemantic[IList] = StructuredList;
576 StructuredList->setSyntacticForm(IList);
577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000579 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000580 if (!VerifyOnly) {
581 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
582 IList->setType(ExprTy);
583 StructuredList->setType(ExprTy);
584 }
Eli Friedman638e1442008-05-25 13:22:35 +0000585 if (hadError)
586 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587
Eli Friedman638e1442008-05-25 13:22:35 +0000588 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000589 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000590 if (VerifyOnly) {
591 if (SemaRef.getLangOptions().CPlusPlus ||
592 (SemaRef.getLangOptions().OpenCL &&
593 IList->getType()->isVectorType())) {
594 hadError = true;
595 }
596 return;
597 }
598
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (StructuredIndex == 1 &&
600 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000601 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000602 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000603 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000604 hadError = true;
605 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000606 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000608 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000609 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000610 // Don't complain for incomplete types, since we'll get an error
611 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000612 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000613 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000614 CurrentObjectType->isArrayType()? 0 :
615 CurrentObjectType->isVectorType()? 1 :
616 CurrentObjectType->isScalarType()? 2 :
617 CurrentObjectType->isUnionType()? 3 :
618 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000619
620 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000621 if (SemaRef.getLangOptions().CPlusPlus) {
622 DK = diag::err_excess_initializers;
623 hadError = true;
624 }
Nate Begeman08634522009-07-07 21:53:06 +0000625 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
626 DK = diag::err_excess_initializers;
627 hadError = true;
628 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000629
Chris Lattner08202542009-02-24 22:50:46 +0000630 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000631 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000632 }
633 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000634
Sebastian Redl14b0c192011-09-24 17:48:00 +0000635 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
636 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000637 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000638 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000639 << FixItHint::CreateRemoval(IList->getLocStart())
640 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000641}
642
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000643void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000644 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000646 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned &Index,
648 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000649 unsigned &StructuredIndex,
650 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000651 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
652 // Explicitly braced initializer for complex type can be real+imaginary
653 // parts.
654 CheckComplexType(Entity, IList, DeclType, Index,
655 StructuredList, StructuredIndex);
656 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000657 CheckScalarType(Entity, IList, DeclType, Index,
658 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000659 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000660 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000661 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000662 } else if (DeclType->isAggregateType()) {
663 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000664 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000665 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000666 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000667 StructuredList, StructuredIndex,
668 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000669 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000670 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000671 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000672 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000674 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000676 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000677 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000678 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
679 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000680 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000681 if (!VerifyOnly)
682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
683 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000684 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 } else if (DeclType->isRecordType()) {
686 // C++ [dcl.init]p14:
687 // [...] If the class is an aggregate (8.5.1), and the initializer
688 // is a brace-enclosed list, see 8.5.1.
689 //
690 // Note: 8.5.1 is handled below; here, we diagnose the case where
691 // we have an initializer list and a destination type that is not
692 // an aggregate.
693 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000694 if (!VerifyOnly)
695 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
696 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000697 hadError = true;
698 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000699 CheckReferenceType(Entity, IList, DeclType, Index,
700 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000701 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000702 if (!VerifyOnly)
703 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
704 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000705 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000706 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000710 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000711 }
712}
713
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000714void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000715 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000716 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 unsigned &Index,
718 InitListExpr *StructuredList,
719 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000720 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000721 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
722 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000723 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000724 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000725 = getStructuredSubobjectInit(IList, Index, ElemType,
726 StructuredList, StructuredIndex,
727 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000728 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000729 newStructuredList, newStructuredIndex);
730 ++StructuredIndex;
731 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000732 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000733 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000734 return CheckScalarType(Entity, IList, ElemType, Index,
735 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000736 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000737 return CheckReferenceType(Entity, IList, ElemType, Index,
738 StructuredList, StructuredIndex);
739 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000740
John McCallfef8b342011-02-21 07:57:55 +0000741 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
742 // arrayType can be incomplete if we're initializing a flexible
743 // array member. There's nothing we can do with the completed
744 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745
John McCallfef8b342011-02-21 07:57:55 +0000746 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
747 CheckStringInit(Str, ElemType, arrayType, SemaRef);
748 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000749 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000750 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000751 }
John McCallfef8b342011-02-21 07:57:55 +0000752
753 // Fall through for subaggregate initialization.
754
755 } else if (SemaRef.getLangOptions().CPlusPlus) {
756 // C++ [dcl.init.aggr]p12:
757 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000758 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000759 // an initializer-list. If the initializer can initialize a
760 // member, the member is initialized. [...]
761
762 // FIXME: Better EqualLoc?
763 InitializationKind Kind =
764 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
765 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
766
767 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000768 if (!VerifyOnly) {
769 ExprResult Result =
770 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
771 if (Result.isInvalid())
772 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000773
Sebastian Redl14b0c192011-09-24 17:48:00 +0000774 UpdateStructuredListElement(StructuredList, StructuredIndex,
775 Result.takeAs<Expr>());
776 }
John McCallfef8b342011-02-21 07:57:55 +0000777 ++Index;
778 return;
779 }
780
781 // Fall through for subaggregate initialization
782 } else {
783 // C99 6.7.8p13:
784 //
785 // The initializer for a structure or union object that has
786 // automatic storage duration shall be either an initializer
787 // list as described below, or a single expression that has
788 // compatible structure or union type. In the latter case, the
789 // initial value of the object, including unnamed members, is
790 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000791 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000792 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000793 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
794 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000795 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000796 if (ExprRes.isInvalid())
797 hadError = true;
798 else {
799 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
800 if (ExprRes.isInvalid())
801 hadError = true;
802 }
803 UpdateStructuredListElement(StructuredList, StructuredIndex,
804 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
John Wiegley429bb272011-04-08 18:41:53 +0000808 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000809 // Fall through for subaggregate initialization
810 }
811
812 // C++ [dcl.init.aggr]p12:
813 //
814 // [...] Otherwise, if the member is itself a non-empty
815 // subaggregate, brace elision is assumed and the initializer is
816 // considered for the initialization of the first member of
817 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000818 if (!SemaRef.getLangOptions().OpenCL &&
819 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000820 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
821 StructuredIndex);
822 ++StructuredIndex;
823 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000824 if (!VerifyOnly) {
825 // We cannot initialize this element, so let
826 // PerformCopyInitialization produce the appropriate diagnostic.
827 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
828 SemaRef.Owned(expr),
829 /*TopLevelOfInitList=*/true);
830 }
John McCallfef8b342011-02-21 07:57:55 +0000831 hadError = true;
832 ++Index;
833 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000834 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000835}
836
Eli Friedman0c706c22011-09-19 23:17:44 +0000837void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
838 InitListExpr *IList, QualType DeclType,
839 unsigned &Index,
840 InitListExpr *StructuredList,
841 unsigned &StructuredIndex) {
842 assert(Index == 0 && "Index in explicit init list must be zero");
843
844 // As an extension, clang supports complex initializers, which initialize
845 // a complex number component-wise. When an explicit initializer list for
846 // a complex number contains two two initializers, this extension kicks in:
847 // it exepcts the initializer list to contain two elements convertible to
848 // the element type of the complex type. The first element initializes
849 // the real part, and the second element intitializes the imaginary part.
850
851 if (IList->getNumInits() != 2)
852 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
853 StructuredIndex);
854
855 // This is an extension in C. (The builtin _Complex type does not exist
856 // in the C++ standard.)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000857 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000858 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
859 << IList->getSourceRange();
860
861 // Initialize the complex number.
862 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
863 InitializedEntity ElementEntity =
864 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
865
866 for (unsigned i = 0; i < 2; ++i) {
867 ElementEntity.setElementIndex(Index);
868 CheckSubElementType(ElementEntity, IList, elementType, Index,
869 StructuredList, StructuredIndex);
870 }
871}
872
873
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000874void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000875 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000876 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000877 InitListExpr *StructuredList,
878 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000879 if (Index >= IList->getNumInits()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000880 // FIXME: Allowed in C++11.
881 if (!VerifyOnly)
882 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
883 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000884 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000885 ++Index;
886 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000887 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000888 }
John McCallb934c2d2010-11-11 00:46:36 +0000889
890 Expr *expr = IList->getInit(Index);
891 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000892 if (!VerifyOnly)
893 SemaRef.Diag(SubIList->getLocStart(),
894 diag::warn_many_braces_around_scalar_init)
895 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000896
897 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
898 StructuredIndex);
899 return;
900 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000901 if (!VerifyOnly)
902 SemaRef.Diag(expr->getSourceRange().getBegin(),
903 diag::err_designator_for_scalar_init)
904 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000905 hadError = true;
906 ++Index;
907 ++StructuredIndex;
908 return;
909 }
910
Sebastian Redl14b0c192011-09-24 17:48:00 +0000911 if (VerifyOnly) {
912 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
913 hadError = true;
914 ++Index;
915 return;
916 }
917
John McCallb934c2d2010-11-11 00:46:36 +0000918 ExprResult Result =
919 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000920 SemaRef.Owned(expr),
921 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000922
923 Expr *ResultExpr = 0;
924
925 if (Result.isInvalid())
926 hadError = true; // types weren't compatible.
927 else {
928 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000929
John McCallb934c2d2010-11-11 00:46:36 +0000930 if (ResultExpr != expr) {
931 // The type was promoted, update initializer list.
932 IList->setInit(Index, ResultExpr);
933 }
934 }
935 if (hadError)
936 ++StructuredIndex;
937 else
938 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
939 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000940}
941
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000942void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
943 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000944 unsigned &Index,
945 InitListExpr *StructuredList,
946 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000947 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000948 // FIXME: It would be wonderful if we could point at the actual member. In
949 // general, it would be useful to pass location information down the stack,
950 // so that we know the location (or decl) of the "current object" being
951 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000952 if (!VerifyOnly)
953 SemaRef.Diag(IList->getLocStart(),
954 diag::err_init_reference_member_uninitialized)
955 << DeclType
956 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000957 hadError = true;
958 ++Index;
959 ++StructuredIndex;
960 return;
961 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000962
963 Expr *expr = IList->getInit(Index);
964 if (isa<InitListExpr>(expr)) {
965 // FIXME: Allowed in C++11.
966 if (!VerifyOnly)
967 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
968 << DeclType << IList->getSourceRange();
969 hadError = true;
970 ++Index;
971 ++StructuredIndex;
972 return;
973 }
974
975 if (VerifyOnly) {
976 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
977 hadError = true;
978 ++Index;
979 return;
980 }
981
982 ExprResult Result =
983 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
984 SemaRef.Owned(expr),
985 /*TopLevelOfInitList=*/true);
986
987 if (Result.isInvalid())
988 hadError = true;
989
990 expr = Result.takeAs<Expr>();
991 IList->setInit(Index, expr);
992
993 if (hadError)
994 ++StructuredIndex;
995 else
996 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
997 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000998}
999
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001000void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001001 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001002 unsigned &Index,
1003 InitListExpr *StructuredList,
1004 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001005 if (Index >= IList->getNumInits())
1006 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
John McCall20e047a2010-10-30 00:11:39 +00001008 const VectorType *VT = DeclType->getAs<VectorType>();
1009 unsigned maxElements = VT->getNumElements();
1010 unsigned numEltsInit = 0;
1011 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001012
John McCall20e047a2010-10-30 00:11:39 +00001013 if (!SemaRef.getLangOptions().OpenCL) {
1014 // If the initializing element is a vector, try to copy-initialize
1015 // instead of breaking it apart (which is doomed to failure anyway).
1016 Expr *Init = IList->getInit(Index);
1017 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001018 if (VerifyOnly) {
1019 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1020 hadError = true;
1021 ++Index;
1022 return;
1023 }
1024
John McCall20e047a2010-10-30 00:11:39 +00001025 ExprResult Result =
1026 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001027 SemaRef.Owned(Init),
1028 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001029
1030 Expr *ResultExpr = 0;
1031 if (Result.isInvalid())
1032 hadError = true; // types weren't compatible.
1033 else {
1034 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
John McCall20e047a2010-10-30 00:11:39 +00001036 if (ResultExpr != Init) {
1037 // The type was promoted, update initializer list.
1038 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001039 }
1040 }
John McCall20e047a2010-10-30 00:11:39 +00001041 if (hadError)
1042 ++StructuredIndex;
1043 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001044 UpdateStructuredListElement(StructuredList, StructuredIndex,
1045 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001046 ++Index;
1047 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001048 }
Mike Stump1eb44332009-09-09 15:08:12 +00001049
John McCall20e047a2010-10-30 00:11:39 +00001050 InitializedEntity ElementEntity =
1051 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001052
John McCall20e047a2010-10-30 00:11:39 +00001053 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1054 // Don't attempt to go past the end of the init list
1055 if (Index >= IList->getNumInits())
1056 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001057
John McCall20e047a2010-10-30 00:11:39 +00001058 ElementEntity.setElementIndex(Index);
1059 CheckSubElementType(ElementEntity, IList, elementType, Index,
1060 StructuredList, StructuredIndex);
1061 }
1062 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001063 }
John McCall20e047a2010-10-30 00:11:39 +00001064
1065 InitializedEntity ElementEntity =
1066 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001067
John McCall20e047a2010-10-30 00:11:39 +00001068 // OpenCL initializers allows vectors to be constructed from vectors.
1069 for (unsigned i = 0; i < maxElements; ++i) {
1070 // Don't attempt to go past the end of the init list
1071 if (Index >= IList->getNumInits())
1072 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001073
John McCall20e047a2010-10-30 00:11:39 +00001074 ElementEntity.setElementIndex(Index);
1075
1076 QualType IType = IList->getInit(Index)->getType();
1077 if (!IType->isVectorType()) {
1078 CheckSubElementType(ElementEntity, IList, elementType, Index,
1079 StructuredList, StructuredIndex);
1080 ++numEltsInit;
1081 } else {
1082 QualType VecType;
1083 const VectorType *IVT = IType->getAs<VectorType>();
1084 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
John McCall20e047a2010-10-30 00:11:39 +00001086 if (IType->isExtVectorType())
1087 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1088 else
1089 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001090 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001091 CheckSubElementType(ElementEntity, IList, VecType, Index,
1092 StructuredList, StructuredIndex);
1093 numEltsInit += numIElts;
1094 }
1095 }
1096
1097 // OpenCL requires all elements to be initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001098 // FIXME: Shouldn't this set hadError to true then?
1099 if (numEltsInit != maxElements && !VerifyOnly)
1100 SemaRef.Diag(IList->getSourceRange().getBegin(),
1101 diag::err_vector_incorrect_num_initializers)
1102 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001103}
1104
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001105void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001106 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001107 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001108 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001109 unsigned &Index,
1110 InitListExpr *StructuredList,
1111 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001112 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1113
Steve Naroff0cca7492008-05-01 22:18:59 +00001114 // Check for the special-case of initializing an array with a string.
1115 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001116 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001117 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001118 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001119 // We place the string literal directly into the resulting
1120 // initializer list. This is the only place where the structure
1121 // of the structured initializer list doesn't match exactly,
1122 // because doing so would involve allocating one character
1123 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001124 if (!VerifyOnly) {
1125 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1126 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1127 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001128 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001129 return;
1130 }
1131 }
John McCallce6c9b72011-02-21 07:22:22 +00001132 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001133 // Check for VLAs; in standard C it would be possible to check this
1134 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1135 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001136 if (!VerifyOnly)
1137 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1138 diag::err_variable_object_no_init)
1139 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001140 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001141 ++Index;
1142 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001143 return;
1144 }
1145
Douglas Gregor05c13a32009-01-22 00:58:24 +00001146 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001147 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1148 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001149 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001150 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001151 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001152 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001153 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001154 maxElementsKnown = true;
1155 }
1156
John McCallce6c9b72011-02-21 07:22:22 +00001157 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001158 while (Index < IList->getNumInits()) {
1159 Expr *Init = IList->getInit(Index);
1160 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001161 // If we're not the subobject that matches up with the '{' for
1162 // the designator, we shouldn't be handling the
1163 // designator. Return immediately.
1164 if (!SubobjectIsDesignatorContext)
1165 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001166
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001167 // Handle this designated initializer. elementIndex will be
1168 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001169 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001170 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001171 StructuredList, StructuredIndex, true,
1172 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001173 hadError = true;
1174 continue;
1175 }
1176
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001177 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001178 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001179 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001180 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001181 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001182
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001183 // If the array is of incomplete type, keep track of the number of
1184 // elements in the initializer.
1185 if (!maxElementsKnown && elementIndex > maxElements)
1186 maxElements = elementIndex;
1187
Douglas Gregor05c13a32009-01-22 00:58:24 +00001188 continue;
1189 }
1190
1191 // If we know the maximum number of elements, and we've already
1192 // hit it, stop consuming elements in the initializer list.
1193 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001194 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001195
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001196 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001197 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001198 Entity);
1199 // Check this element.
1200 CheckSubElementType(ElementEntity, IList, elementType, Index,
1201 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001202 ++elementIndex;
1203
1204 // If the array is of incomplete type, keep track of the number of
1205 // elements in the initializer.
1206 if (!maxElementsKnown && elementIndex > maxElements)
1207 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001208 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001209 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001210 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001211 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001212 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001213 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001214 // Sizing an array implicitly to zero is not allowed by ISO C,
1215 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001216 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001217 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001218 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001219
Mike Stump1eb44332009-09-09 15:08:12 +00001220 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001221 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001222 }
1223}
1224
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001225bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1226 Expr *InitExpr,
1227 FieldDecl *Field,
1228 bool TopLevelObject) {
1229 // Handle GNU flexible array initializers.
1230 unsigned FlexArrayDiag;
1231 if (isa<InitListExpr>(InitExpr) &&
1232 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1233 // Empty flexible array init always allowed as an extension
1234 FlexArrayDiag = diag::ext_flexible_array_init;
1235 } else if (SemaRef.getLangOptions().CPlusPlus) {
1236 // Disallow flexible array init in C++; it is not required for gcc
1237 // compatibility, and it needs work to IRGen correctly in general.
1238 FlexArrayDiag = diag::err_flexible_array_init;
1239 } else if (!TopLevelObject) {
1240 // Disallow flexible array init on non-top-level object
1241 FlexArrayDiag = diag::err_flexible_array_init;
1242 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1243 // Disallow flexible array init on anything which is not a variable.
1244 FlexArrayDiag = diag::err_flexible_array_init;
1245 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1246 // Disallow flexible array init on local variables.
1247 FlexArrayDiag = diag::err_flexible_array_init;
1248 } else {
1249 // Allow other cases.
1250 FlexArrayDiag = diag::ext_flexible_array_init;
1251 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001252
1253 if (!VerifyOnly) {
1254 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1255 FlexArrayDiag)
1256 << InitExpr->getSourceRange().getBegin();
1257 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1258 << Field;
1259 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001260
1261 return FlexArrayDiag != diag::ext_flexible_array_init;
1262}
1263
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001264void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001265 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001266 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001267 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001268 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001269 unsigned &Index,
1270 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001271 unsigned &StructuredIndex,
1272 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001273 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Eli Friedmanb85f7072008-05-19 19:16:24 +00001275 // If the record is invalid, some of it's members are invalid. To avoid
1276 // confusion, we forgo checking the intializer for the entire record.
1277 if (structDecl->isInvalidDecl()) {
1278 hadError = true;
1279 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001280 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001281
1282 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001283 if (!VerifyOnly) {
1284 // Value-initialize the first named member of the union.
1285 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1286 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1287 Field != FieldEnd; ++Field) {
1288 if (Field->getDeclName()) {
1289 StructuredList->setInitializedFieldInUnion(*Field);
1290 break;
1291 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001292 }
1293 }
1294 return;
1295 }
1296
Douglas Gregor05c13a32009-01-22 00:58:24 +00001297 // If structDecl is a forward declaration, this loop won't do
1298 // anything except look at designated initializers; That's okay,
1299 // because an error should get printed out elsewhere. It might be
1300 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001301 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001302 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001303 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001304 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001305 while (Index < IList->getNumInits()) {
1306 Expr *Init = IList->getInit(Index);
1307
1308 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001309 // If we're not the subobject that matches up with the '{' for
1310 // the designator, we shouldn't be handling the
1311 // designator. Return immediately.
1312 if (!SubobjectIsDesignatorContext)
1313 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001314
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001315 // Handle this designated initializer. Field will be updated to
1316 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001317 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001319 StructuredList, StructuredIndex,
1320 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001321 hadError = true;
1322
Douglas Gregordfb5e592009-02-12 19:00:39 +00001323 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001324
1325 // Disable check for missing fields when designators are used.
1326 // This matches gcc behaviour.
1327 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001328 continue;
1329 }
1330
1331 if (Field == FieldEnd) {
1332 // We've run out of fields. We're done.
1333 break;
1334 }
1335
Douglas Gregordfb5e592009-02-12 19:00:39 +00001336 // We've already initialized a member of a union. We're done.
1337 if (InitializedSomething && DeclType->isUnionType())
1338 break;
1339
Douglas Gregor44b43212008-12-11 16:49:14 +00001340 // If we've hit the flexible array member at the end, we're done.
1341 if (Field->getType()->isIncompleteArrayType())
1342 break;
1343
Douglas Gregor0bb76892009-01-29 16:53:55 +00001344 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001345 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001346 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001347 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001348 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001349
Douglas Gregor54001c12011-06-29 21:51:31 +00001350 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001351 bool InvalidUse;
1352 if (VerifyOnly)
1353 InvalidUse = !SemaRef.CanUseDecl(*Field);
1354 else
1355 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1356 IList->getInit(Index)->getLocStart());
1357 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001358 ++Index;
1359 ++Field;
1360 hadError = true;
1361 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001362 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001363
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001364 InitializedEntity MemberEntity =
1365 InitializedEntity::InitializeMember(*Field, &Entity);
1366 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1367 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001368 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001369
Sebastian Redl14b0c192011-09-24 17:48:00 +00001370 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001371 // Initialize the first field within the union.
1372 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001373 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001374
1375 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001376 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001377
John McCall80639de2010-03-11 19:32:38 +00001378 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001379 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1380 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1381 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001382 // It is possible we have one or more unnamed bitfields remaining.
1383 // Find first (if any) named field and emit warning.
1384 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1385 it != end; ++it) {
1386 if (!it->isUnnamedBitfield()) {
1387 SemaRef.Diag(IList->getSourceRange().getEnd(),
1388 diag::warn_missing_field_initializers) << it->getName();
1389 break;
1390 }
1391 }
1392 }
1393
Mike Stump1eb44332009-09-09 15:08:12 +00001394 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001395 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001396 return;
1397
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001398 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1399 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001400 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001401 ++Index;
1402 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001403 }
1404
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001405 InitializedEntity MemberEntity =
1406 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001408 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001410 StructuredList, StructuredIndex);
1411 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001412 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001413 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001414}
Steve Naroff0cca7492008-05-01 22:18:59 +00001415
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001416/// \brief Expand a field designator that refers to a member of an
1417/// anonymous struct or union into a series of field designators that
1418/// refers to the field within the appropriate subobject.
1419///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001420static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001421 DesignatedInitExpr *DIE,
1422 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001423 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001424 typedef DesignatedInitExpr::Designator Designator;
1425
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001426 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001427 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001428 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1429 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1430 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001431 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001432 DIE->getDesignator(DesigIdx)->getDotLoc(),
1433 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1434 else
1435 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1436 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001437 assert(isa<FieldDecl>(*PI));
1438 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001439 }
1440
1441 // Expand the current designator into the set of replacement
1442 // designators, so we have a full subobject path down to where the
1443 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001444 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001445 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001446}
Mike Stump1eb44332009-09-09 15:08:12 +00001447
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001448/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001449/// corresponds to FieldName.
1450static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1451 IdentifierInfo *FieldName) {
1452 assert(AnonField->isAnonymousStructOrUnion());
1453 Decl *NextDecl = AnonField->getNextDeclInContext();
1454 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1455 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1456 return IF;
1457 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001458 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001459 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001460}
1461
Sebastian Redl14b0c192011-09-24 17:48:00 +00001462static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1463 DesignatedInitExpr *DIE) {
1464 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1465 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1466 for (unsigned I = 0; I < NumIndexExprs; ++I)
1467 IndexExprs[I] = DIE->getSubExpr(I + 1);
1468 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1469 DIE->size(), IndexExprs.data(),
1470 NumIndexExprs, DIE->getEqualOrColonLoc(),
1471 DIE->usesGNUSyntax(), DIE->getInit());
1472}
1473
Douglas Gregor05c13a32009-01-22 00:58:24 +00001474/// @brief Check the well-formedness of a C99 designated initializer.
1475///
1476/// Determines whether the designated initializer @p DIE, which
1477/// resides at the given @p Index within the initializer list @p
1478/// IList, is well-formed for a current object of type @p DeclType
1479/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001480/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001481/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001482///
1483/// @param IList The initializer list in which this designated
1484/// initializer occurs.
1485///
Douglas Gregor71199712009-04-15 04:56:10 +00001486/// @param DIE The designated initializer expression.
1487///
1488/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001489///
1490/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1491/// into which the designation in @p DIE should refer.
1492///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001493/// @param NextField If non-NULL and the first designator in @p DIE is
1494/// a field, this will be set to the field declaration corresponding
1495/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001496///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001497/// @param NextElementIndex If non-NULL and the first designator in @p
1498/// DIE is an array designator or GNU array-range designator, this
1499/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001500///
1501/// @param Index Index into @p IList where the designated initializer
1502/// @p DIE occurs.
1503///
Douglas Gregor4c678342009-01-28 21:54:33 +00001504/// @param StructuredList The initializer list expression that
1505/// describes all of the subobject initializers in the order they'll
1506/// actually be initialized.
1507///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001508/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001509bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001510InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001511 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001512 DesignatedInitExpr *DIE,
1513 unsigned DesigIdx,
1514 QualType &CurrentObjectType,
1515 RecordDecl::field_iterator *NextField,
1516 llvm::APSInt *NextElementIndex,
1517 unsigned &Index,
1518 InitListExpr *StructuredList,
1519 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001520 bool FinishSubobjectInit,
1521 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001522 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001523 // Check the actual initialization for the designated object type.
1524 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001525
1526 // Temporarily remove the designator expression from the
1527 // initializer list that the child calls see, so that we don't try
1528 // to re-process the designator.
1529 unsigned OldIndex = Index;
1530 IList->setInit(OldIndex, DIE->getInit());
1531
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001532 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001533 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001534
1535 // Restore the designated initializer expression in the syntactic
1536 // form of the initializer list.
1537 if (IList->getInit(OldIndex) != DIE->getInit())
1538 DIE->setInit(IList->getInit(OldIndex));
1539 IList->setInit(OldIndex, DIE);
1540
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001542 }
1543
Douglas Gregor71199712009-04-15 04:56:10 +00001544 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001545 bool IsFirstDesignator = (DesigIdx == 0);
1546 if (!VerifyOnly) {
1547 assert((IsFirstDesignator || StructuredList) &&
1548 "Need a non-designated initializer list to start from");
1549
1550 // Determine the structural initializer list that corresponds to the
1551 // current subobject.
1552 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1553 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1554 StructuredList, StructuredIndex,
1555 SourceRange(D->getStartLocation(),
1556 DIE->getSourceRange().getEnd()));
1557 assert(StructuredList && "Expected a structured initializer list");
1558 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001559
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001560 if (D->isFieldDesignator()) {
1561 // C99 6.7.8p7:
1562 //
1563 // If a designator has the form
1564 //
1565 // . identifier
1566 //
1567 // then the current object (defined below) shall have
1568 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001569 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001570 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 if (!RT) {
1572 SourceLocation Loc = D->getDotLoc();
1573 if (Loc.isInvalid())
1574 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001575 if (!VerifyOnly)
1576 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1577 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001578 ++Index;
1579 return true;
1580 }
1581
Douglas Gregor4c678342009-01-28 21:54:33 +00001582 // Note: we perform a linear search of the fields here, despite
1583 // the fact that we have a faster lookup method, because we always
1584 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001585 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001586 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001587 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001588 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001589 Field = RT->getDecl()->field_begin(),
1590 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001591 for (; Field != FieldEnd; ++Field) {
1592 if (Field->isUnnamedBitfield())
1593 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594
Francois Picheta0e27f02010-12-22 03:46:10 +00001595 // If we find a field representing an anonymous field, look in the
1596 // IndirectFieldDecl that follow for the designated initializer.
1597 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1598 if (IndirectFieldDecl *IF =
1599 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001600 // In verify mode, don't modify the original.
1601 if (VerifyOnly)
1602 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001603 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1604 D = DIE->getDesignator(DesigIdx);
1605 break;
1606 }
1607 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001608 if (KnownField && KnownField == *Field)
1609 break;
1610 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001611 break;
1612
1613 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001614 }
1615
Douglas Gregor4c678342009-01-28 21:54:33 +00001616 if (Field == FieldEnd) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001617 if (VerifyOnly)
1618 return true; // No typo correction when just trying this out.
1619
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001620 // There was no normal field in the struct with the designated
1621 // name. Perform another lookup for this name, which may find
1622 // something that we can't designate (e.g., a member function),
1623 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001624 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001625 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001626 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001627 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001628 // Name lookup didn't find anything. Determine whether this
1629 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001631 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001632 TypoCorrection Corrected = SemaRef.CorrectTypo(
1633 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1634 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1635 RT->getDecl(), false, Sema::CTC_NoKeywords);
1636 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001637 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001638 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001639 std::string CorrectedStr(
1640 Corrected.getAsString(SemaRef.getLangOptions()));
1641 std::string CorrectedQuotedStr(
1642 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001643 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001644 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001645 << FieldName << CurrentObjectType << CorrectedQuotedStr
1646 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001647 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001648 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001649 } else {
1650 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1651 << FieldName << CurrentObjectType;
1652 ++Index;
1653 return true;
1654 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001655 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001656
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001657 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001658 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001659 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001660 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001661 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001662 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001663 ++Index;
1664 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001665 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001666
Francois Picheta0e27f02010-12-22 03:46:10 +00001667 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001668 // The replacement field comes from typo correction; find it
1669 // in the list of fields.
1670 FieldIndex = 0;
1671 Field = RT->getDecl()->field_begin();
1672 for (; Field != FieldEnd; ++Field) {
1673 if (Field->isUnnamedBitfield())
1674 continue;
1675
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001677 Field->getIdentifier() == ReplacementField->getIdentifier())
1678 break;
1679
1680 ++FieldIndex;
1681 }
1682 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001683 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001684
1685 // All of the fields of a union are located at the same place in
1686 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001687 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001688 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001689 if (!VerifyOnly)
1690 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001691 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001692
Douglas Gregor54001c12011-06-29 21:51:31 +00001693 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001694 bool InvalidUse;
1695 if (VerifyOnly)
1696 InvalidUse = !SemaRef.CanUseDecl(*Field);
1697 else
1698 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1699 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001700 ++Index;
1701 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001702 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001703
Sebastian Redl14b0c192011-09-24 17:48:00 +00001704 if (!VerifyOnly) {
1705 // Update the designator with the field declaration.
1706 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Sebastian Redl14b0c192011-09-24 17:48:00 +00001708 // Make sure that our non-designated initializer list has space
1709 // for a subobject corresponding to this field.
1710 if (FieldIndex >= StructuredList->getNumInits())
1711 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1712 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001713
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001714 // This designator names a flexible array member.
1715 if (Field->getType()->isIncompleteArrayType()) {
1716 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001717 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001718 // We can't designate an object within the flexible array
1719 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001720 if (!VerifyOnly) {
1721 DesignatedInitExpr::Designator *NextD
1722 = DIE->getDesignator(DesigIdx + 1);
1723 SemaRef.Diag(NextD->getStartLocation(),
1724 diag::err_designator_into_flexible_array_member)
1725 << SourceRange(NextD->getStartLocation(),
1726 DIE->getSourceRange().getEnd());
1727 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1728 << *Field;
1729 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001730 Invalid = true;
1731 }
1732
Chris Lattner9046c222010-10-10 17:49:49 +00001733 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1734 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001735 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001736 if (!VerifyOnly) {
1737 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1738 diag::err_flexible_array_init_needs_braces)
1739 << DIE->getInit()->getSourceRange();
1740 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1741 << *Field;
1742 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001743 Invalid = true;
1744 }
1745
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001746 // Check GNU flexible array initializer.
1747 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1748 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001749 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001750
1751 if (Invalid) {
1752 ++Index;
1753 return true;
1754 }
1755
1756 // Initialize the array.
1757 bool prevHadError = hadError;
1758 unsigned newStructuredIndex = FieldIndex;
1759 unsigned OldIndex = Index;
1760 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001761
1762 InitializedEntity MemberEntity =
1763 InitializedEntity::InitializeMember(*Field, &Entity);
1764 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001765 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001766
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001767 IList->setInit(OldIndex, DIE);
1768 if (hadError && !prevHadError) {
1769 ++Field;
1770 ++FieldIndex;
1771 if (NextField)
1772 *NextField = Field;
1773 StructuredIndex = FieldIndex;
1774 return true;
1775 }
1776 } else {
1777 // Recurse to check later designated subobjects.
1778 QualType FieldType = (*Field)->getType();
1779 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001781 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001782 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001783 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1784 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001785 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001786 true, false))
1787 return true;
1788 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001789
1790 // Find the position of the next field to be initialized in this
1791 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001792 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001793 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001794
1795 // If this the first designator, our caller will continue checking
1796 // the rest of this struct/class/union subobject.
1797 if (IsFirstDesignator) {
1798 if (NextField)
1799 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001800 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001801 return false;
1802 }
1803
Douglas Gregor34e79462009-01-28 23:36:17 +00001804 if (!FinishSubobjectInit)
1805 return false;
1806
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001807 // We've already initialized something in the union; we're done.
1808 if (RT->getDecl()->isUnion())
1809 return hadError;
1810
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001811 // Check the remaining fields within this class/struct/union subobject.
1812 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001813
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001814 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001815 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001816 return hadError && !prevHadError;
1817 }
1818
1819 // C99 6.7.8p6:
1820 //
1821 // If a designator has the form
1822 //
1823 // [ constant-expression ]
1824 //
1825 // then the current object (defined below) shall have array
1826 // type and the expression shall be an integer constant
1827 // expression. If the array is of unknown size, any
1828 // nonnegative value is valid.
1829 //
1830 // Additionally, cope with the GNU extension that permits
1831 // designators of the form
1832 //
1833 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001834 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001835 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001836 if (!VerifyOnly)
1837 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1838 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001839 ++Index;
1840 return true;
1841 }
1842
1843 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001844 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1845 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001846 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001847 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001848 DesignatedEndIndex = DesignatedStartIndex;
1849 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001850 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001851
Mike Stump1eb44332009-09-09 15:08:12 +00001852 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001853 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001854 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001855 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001856 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001857
Chris Lattnere0fd8322011-02-19 22:28:58 +00001858 // Codegen can't handle evaluating array range designators that have side
1859 // effects, because we replicate the AST value for each initialized element.
1860 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1861 // elements with something that has a side effect, so codegen can emit an
1862 // "error unsupported" error instead of miscompiling the app.
1863 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001864 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001865 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001866 }
1867
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001868 if (isa<ConstantArrayType>(AT)) {
1869 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001870 DesignatedStartIndex
1871 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001872 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001873 DesignatedEndIndex
1874 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001875 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1876 if (DesignatedEndIndex >= MaxElements) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001877 if (VerifyOnly)
1878 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1879 diag::err_array_designator_too_large)
1880 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1881 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001882 ++Index;
1883 return true;
1884 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001885 } else {
1886 // Make sure the bit-widths and signedness match.
1887 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001888 DesignatedEndIndex
1889 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001890 else if (DesignatedStartIndex.getBitWidth() <
1891 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001892 DesignatedStartIndex
1893 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001894 DesignatedStartIndex.setIsUnsigned(true);
1895 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001896 }
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Douglas Gregor4c678342009-01-28 21:54:33 +00001898 // Make sure that our non-designated initializer list has space
1899 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001900 if (!VerifyOnly &&
1901 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001902 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001903 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001904
Douglas Gregor34e79462009-01-28 23:36:17 +00001905 // Repeatedly perform subobject initializations in the range
1906 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001907
Douglas Gregor34e79462009-01-28 23:36:17 +00001908 // Move to the next designator
1909 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1910 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001911
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001912 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001913 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001914
Douglas Gregor34e79462009-01-28 23:36:17 +00001915 while (DesignatedStartIndex <= DesignatedEndIndex) {
1916 // Recurse to check later designated subobjects.
1917 QualType ElementType = AT->getElementType();
1918 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001919
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001920 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1922 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001923 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001924 (DesignatedStartIndex == DesignatedEndIndex),
1925 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001926 return true;
1927
1928 // Move to the next index in the array that we'll be initializing.
1929 ++DesignatedStartIndex;
1930 ElementIndex = DesignatedStartIndex.getZExtValue();
1931 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001932
1933 // If this the first designator, our caller will continue checking
1934 // the rest of this array subobject.
1935 if (IsFirstDesignator) {
1936 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001937 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001938 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001939 return false;
1940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Douglas Gregor34e79462009-01-28 23:36:17 +00001942 if (!FinishSubobjectInit)
1943 return false;
1944
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001945 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001946 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001947 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001948 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001949 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001950 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001951}
1952
Douglas Gregor4c678342009-01-28 21:54:33 +00001953// Get the structured initializer list for a subobject of type
1954// @p CurrentObjectType.
1955InitListExpr *
1956InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1957 QualType CurrentObjectType,
1958 InitListExpr *StructuredList,
1959 unsigned StructuredIndex,
1960 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001961 if (VerifyOnly)
1962 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00001963 Expr *ExistingInit = 0;
1964 if (!StructuredList)
1965 ExistingInit = SyntacticToSemantic[IList];
1966 else if (StructuredIndex < StructuredList->getNumInits())
1967 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor4c678342009-01-28 21:54:33 +00001969 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1970 return Result;
1971
1972 if (ExistingInit) {
1973 // We are creating an initializer list that initializes the
1974 // subobjects of the current object, but there was already an
1975 // initialization that completely initialized the current
1976 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001977 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001978 // struct X { int a, b; };
1979 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001980 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001981 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1982 // designated initializer re-initializes the whole
1983 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001984 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001985 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001986 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001987 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001988 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001989 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001990 << ExistingInit->getSourceRange();
1991 }
1992
Mike Stump1eb44332009-09-09 15:08:12 +00001993 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001994 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1995 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001996 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001997
Douglas Gregor63982352010-07-13 18:40:04 +00001998 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001999
Douglas Gregorfa219202009-03-20 23:58:33 +00002000 // Pre-allocate storage for the structured initializer list.
2001 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002002 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002003 bool GotNumInits = false;
2004 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002005 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002006 GotNumInits = true;
2007 } else if (Index < IList->getNumInits()) {
2008 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002009 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002010 GotNumInits = true;
2011 }
Douglas Gregor08457732009-03-21 18:13:52 +00002012 }
2013
Mike Stump1eb44332009-09-09 15:08:12 +00002014 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002015 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2016 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2017 NumElements = CAType->getSize().getZExtValue();
2018 // Simple heuristic so that we don't allocate a very large
2019 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002020 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002021 NumElements = 0;
2022 }
John McCall183700f2009-09-21 23:43:11 +00002023 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002024 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002025 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002026 RecordDecl *RDecl = RType->getDecl();
2027 if (RDecl->isUnion())
2028 NumElements = 1;
2029 else
Mike Stump1eb44332009-09-09 15:08:12 +00002030 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002031 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002032 }
2033
Douglas Gregor08457732009-03-21 18:13:52 +00002034 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002035 NumElements = IList->getNumInits();
2036
Ted Kremenek709210f2010-04-13 23:39:13 +00002037 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002038
Douglas Gregor4c678342009-01-28 21:54:33 +00002039 // Link this new initializer list into the structured initializer
2040 // lists.
2041 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002042 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002043 else {
2044 Result->setSyntacticForm(IList);
2045 SyntacticToSemantic[IList] = Result;
2046 }
2047
2048 return Result;
2049}
2050
2051/// Update the initializer at index @p StructuredIndex within the
2052/// structured initializer list to the value @p expr.
2053void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2054 unsigned &StructuredIndex,
2055 Expr *expr) {
2056 // No structured initializer list to update
2057 if (!StructuredList)
2058 return;
2059
Ted Kremenek709210f2010-04-13 23:39:13 +00002060 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2061 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002062 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002063 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002064 diag::warn_initializer_overrides)
2065 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002066 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002067 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002068 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002069 << PrevInit->getSourceRange();
2070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Douglas Gregor4c678342009-01-28 21:54:33 +00002072 ++StructuredIndex;
2073}
2074
Douglas Gregor05c13a32009-01-22 00:58:24 +00002075/// Check that the given Index expression is a valid array designator
2076/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002077/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002078/// and produces a reasonable diagnostic if there is a
2079/// failure. Returns true if there was an error, false otherwise. If
2080/// everything went okay, Value will receive the value of the constant
2081/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002082static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002083CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002084 SourceLocation Loc = Index->getSourceRange().getBegin();
2085
2086 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002087 if (S.VerifyIntegerConstantExpression(Index, &Value))
2088 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002089
Chris Lattner3bf68932009-04-25 21:59:05 +00002090 if (Value.isSigned() && Value.isNegative())
2091 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002092 << Value.toString(10) << Index->getSourceRange();
2093
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002094 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002095 return false;
2096}
2097
John McCall60d7b3a2010-08-24 06:29:42 +00002098ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002099 SourceLocation Loc,
2100 bool GNUSyntax,
2101 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002102 typedef DesignatedInitExpr::Designator ASTDesignator;
2103
2104 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002105 SmallVector<ASTDesignator, 32> Designators;
2106 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002107
2108 // Build designators and check array designator expressions.
2109 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2110 const Designator &D = Desig.getDesignator(Idx);
2111 switch (D.getKind()) {
2112 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002113 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002114 D.getFieldLoc()));
2115 break;
2116
2117 case Designator::ArrayDesignator: {
2118 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2119 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002120 if (!Index->isTypeDependent() &&
2121 !Index->isValueDependent() &&
2122 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002123 Invalid = true;
2124 else {
2125 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002126 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002127 D.getRBracketLoc()));
2128 InitExpressions.push_back(Index);
2129 }
2130 break;
2131 }
2132
2133 case Designator::ArrayRangeDesignator: {
2134 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2135 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2136 llvm::APSInt StartValue;
2137 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002138 bool StartDependent = StartIndex->isTypeDependent() ||
2139 StartIndex->isValueDependent();
2140 bool EndDependent = EndIndex->isTypeDependent() ||
2141 EndIndex->isValueDependent();
2142 if ((!StartDependent &&
2143 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2144 (!EndDependent &&
2145 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002146 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002147 else {
2148 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002149 if (StartDependent || EndDependent) {
2150 // Nothing to compute.
2151 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002152 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002153 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002154 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002155
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002156 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002157 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002158 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002159 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2160 Invalid = true;
2161 } else {
2162 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002163 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002164 D.getEllipsisLoc(),
2165 D.getRBracketLoc()));
2166 InitExpressions.push_back(StartIndex);
2167 InitExpressions.push_back(EndIndex);
2168 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002169 }
2170 break;
2171 }
2172 }
2173 }
2174
2175 if (Invalid || Init.isInvalid())
2176 return ExprError();
2177
2178 // Clear out the expressions within the designation.
2179 Desig.ClearExprs(*this);
2180
2181 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002182 = DesignatedInitExpr::Create(Context,
2183 Designators.data(), Designators.size(),
2184 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002185 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002187 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002188 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2189 << DIE->getSourceRange();
2190 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002191 Diag(DIE->getLocStart(), diag::ext_designated_init)
2192 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002193
Douglas Gregor05c13a32009-01-22 00:58:24 +00002194 return Owned(DIE);
2195}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002196
Douglas Gregor20093b42009-12-09 23:02:17 +00002197//===----------------------------------------------------------------------===//
2198// Initialization entity
2199//===----------------------------------------------------------------------===//
2200
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002202 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002203 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002204{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002205 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2206 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002207 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002208 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002209 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002210 Type = VT->getElementType();
2211 } else {
2212 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2213 assert(CT && "Unexpected type");
2214 Kind = EK_ComplexElement;
2215 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002216 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002217}
2218
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002220 CXXBaseSpecifier *Base,
2221 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002222{
2223 InitializedEntity Result;
2224 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002225 Result.Base = reinterpret_cast<uintptr_t>(Base);
2226 if (IsInheritedVirtualBase)
2227 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002228
Douglas Gregord6542d82009-12-22 15:35:07 +00002229 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002230 return Result;
2231}
2232
Douglas Gregor99a2e602009-12-16 01:38:02 +00002233DeclarationName InitializedEntity::getName() const {
2234 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002235 case EK_Parameter: {
2236 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2237 return (D ? D->getDeclName() : DeclarationName());
2238 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002239
2240 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002241 case EK_Member:
2242 return VariableOrMember->getDeclName();
2243
2244 case EK_Result:
2245 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002246 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002247 case EK_Temporary:
2248 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002249 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002250 case EK_ArrayElement:
2251 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002252 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002253 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002254 return DeclarationName();
2255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002256
Douglas Gregor99a2e602009-12-16 01:38:02 +00002257 // Silence GCC warning
2258 return DeclarationName();
2259}
2260
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002261DeclaratorDecl *InitializedEntity::getDecl() const {
2262 switch (getKind()) {
2263 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002264 case EK_Member:
2265 return VariableOrMember;
2266
John McCallf85e1932011-06-15 23:02:42 +00002267 case EK_Parameter:
2268 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2269
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002270 case EK_Result:
2271 case EK_Exception:
2272 case EK_New:
2273 case EK_Temporary:
2274 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002275 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002276 case EK_ArrayElement:
2277 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002278 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002279 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002280 return 0;
2281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002282
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002283 // Silence GCC warning
2284 return 0;
2285}
2286
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002287bool InitializedEntity::allowsNRVO() const {
2288 switch (getKind()) {
2289 case EK_Result:
2290 case EK_Exception:
2291 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002292
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002293 case EK_Variable:
2294 case EK_Parameter:
2295 case EK_Member:
2296 case EK_New:
2297 case EK_Temporary:
2298 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002299 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002300 case EK_ArrayElement:
2301 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002302 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002303 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002304 break;
2305 }
2306
2307 return false;
2308}
2309
Douglas Gregor20093b42009-12-09 23:02:17 +00002310//===----------------------------------------------------------------------===//
2311// Initialization sequence
2312//===----------------------------------------------------------------------===//
2313
2314void InitializationSequence::Step::Destroy() {
2315 switch (Kind) {
2316 case SK_ResolveAddressOfOverloadedFunction:
2317 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002318 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002319 case SK_CastDerivedToBaseLValue:
2320 case SK_BindReference:
2321 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002322 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002323 case SK_UserConversion:
2324 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002325 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002326 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002327 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002328 case SK_ListConstructorCall:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002329 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002330 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002331 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002332 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002333 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002334 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002335 case SK_PassByIndirectCopyRestore:
2336 case SK_PassByIndirectRestore:
2337 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002338 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339
Douglas Gregor20093b42009-12-09 23:02:17 +00002340 case SK_ConversionSequence:
2341 delete ICS;
2342 }
2343}
2344
Douglas Gregorb70cf442010-03-26 20:14:36 +00002345bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002346 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002347}
2348
2349bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002350 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002351 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002352
Douglas Gregorb70cf442010-03-26 20:14:36 +00002353 switch (getFailureKind()) {
2354 case FK_TooManyInitsForReference:
2355 case FK_ArrayNeedsInitList:
2356 case FK_ArrayNeedsInitListOrStringLiteral:
2357 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2358 case FK_NonConstLValueReferenceBindingToTemporary:
2359 case FK_NonConstLValueReferenceBindingToUnrelated:
2360 case FK_RValueReferenceBindingToLValue:
2361 case FK_ReferenceInitDropsQualifiers:
2362 case FK_ReferenceInitFailed:
2363 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002364 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002365 case FK_TooManyInitsForScalar:
2366 case FK_ReferenceBindingToInitList:
2367 case FK_InitListBadDestinationType:
2368 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002369 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002370 case FK_ArrayTypeMismatch:
2371 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002372 case FK_ListInitializationFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002373 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002374
Douglas Gregorb70cf442010-03-26 20:14:36 +00002375 case FK_ReferenceInitOverloadFailed:
2376 case FK_UserConversionOverloadFailed:
2377 case FK_ConstructorOverloadFailed:
2378 return FailedOverloadResult == OR_Ambiguous;
2379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002380
Douglas Gregorb70cf442010-03-26 20:14:36 +00002381 return false;
2382}
2383
Douglas Gregord6e44a32010-04-16 22:09:46 +00002384bool InitializationSequence::isConstructorInitialization() const {
2385 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2386}
2387
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002388bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2389 const Expr *Initializer,
2390 bool *isInitializerConstant,
2391 APValue *ConstantValue) const {
2392 if (Steps.empty() || Initializer->isValueDependent())
2393 return false;
2394
2395 const Step &LastStep = Steps.back();
2396 if (LastStep.Kind != SK_ConversionSequence)
2397 return false;
2398
2399 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2400 const StandardConversionSequence *SCS = NULL;
2401 switch (ICS.getKind()) {
2402 case ImplicitConversionSequence::StandardConversion:
2403 SCS = &ICS.Standard;
2404 break;
2405 case ImplicitConversionSequence::UserDefinedConversion:
2406 SCS = &ICS.UserDefined.After;
2407 break;
2408 case ImplicitConversionSequence::AmbiguousConversion:
2409 case ImplicitConversionSequence::EllipsisConversion:
2410 case ImplicitConversionSequence::BadConversion:
2411 return false;
2412 }
2413
2414 // Check if SCS represents a narrowing conversion, according to C++0x
2415 // [dcl.init.list]p7:
2416 //
2417 // A narrowing conversion is an implicit conversion ...
2418 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2419 QualType FromType = SCS->getToType(0);
2420 QualType ToType = SCS->getToType(1);
2421 switch (PossibleNarrowing) {
2422 // * from a floating-point type to an integer type, or
2423 //
2424 // * from an integer type or unscoped enumeration type to a floating-point
2425 // type, except where the source is a constant expression and the actual
2426 // value after conversion will fit into the target type and will produce
2427 // the original value when converted back to the original type, or
2428 case ICK_Floating_Integral:
2429 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2430 *isInitializerConstant = false;
2431 return true;
2432 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2433 llvm::APSInt IntConstantValue;
2434 if (Initializer &&
2435 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2436 // Convert the integer to the floating type.
2437 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2438 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2439 llvm::APFloat::rmNearestTiesToEven);
2440 // And back.
2441 llvm::APSInt ConvertedValue = IntConstantValue;
2442 bool ignored;
2443 Result.convertToInteger(ConvertedValue,
2444 llvm::APFloat::rmTowardZero, &ignored);
2445 // If the resulting value is different, this was a narrowing conversion.
2446 if (IntConstantValue != ConvertedValue) {
2447 *isInitializerConstant = true;
2448 *ConstantValue = APValue(IntConstantValue);
2449 return true;
2450 }
2451 } else {
2452 // Variables are always narrowings.
2453 *isInitializerConstant = false;
2454 return true;
2455 }
2456 }
2457 return false;
2458
2459 // * from long double to double or float, or from double to float, except
2460 // where the source is a constant expression and the actual value after
2461 // conversion is within the range of values that can be represented (even
2462 // if it cannot be represented exactly), or
2463 case ICK_Floating_Conversion:
2464 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2465 // FromType is larger than ToType.
2466 Expr::EvalResult InitializerValue;
2467 // FIXME: Check whether Initializer is a constant expression according
2468 // to C++0x [expr.const], rather than just whether it can be folded.
2469 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2470 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2471 // Constant! (Except for FIXME above.)
2472 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2473 // Convert the source value into the target type.
2474 bool ignored;
2475 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2476 Ctx.getFloatTypeSemantics(ToType),
2477 llvm::APFloat::rmNearestTiesToEven, &ignored);
2478 // If there was no overflow, the source value is within the range of
2479 // values that can be represented.
2480 if (ConvertStatus & llvm::APFloat::opOverflow) {
2481 *isInitializerConstant = true;
2482 *ConstantValue = InitializerValue.Val;
2483 return true;
2484 }
2485 } else {
2486 *isInitializerConstant = false;
2487 return true;
2488 }
2489 }
2490 return false;
2491
2492 // * from an integer type or unscoped enumeration type to an integer type
2493 // that cannot represent all the values of the original type, except where
2494 // the source is a constant expression and the actual value after
2495 // conversion will fit into the target type and will produce the original
2496 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002497 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002498 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2499 // Boolean conversions can be from pointers and pointers to members
2500 // [conv.bool], and those aren't considered narrowing conversions.
2501 return false;
2502 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002503 case ICK_Integral_Conversion: {
2504 assert(FromType->isIntegralOrUnscopedEnumerationType());
2505 assert(ToType->isIntegralOrUnscopedEnumerationType());
2506 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2507 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2508 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2509 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2510
2511 if (FromWidth > ToWidth ||
2512 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2513 // Not all values of FromType can be represented in ToType.
2514 llvm::APSInt InitializerValue;
2515 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2516 *isInitializerConstant = true;
2517 *ConstantValue = APValue(InitializerValue);
2518
2519 // Add a bit to the InitializerValue so we don't have to worry about
2520 // signed vs. unsigned comparisons.
2521 InitializerValue = InitializerValue.extend(
2522 InitializerValue.getBitWidth() + 1);
2523 // Convert the initializer to and from the target width and signed-ness.
2524 llvm::APSInt ConvertedValue = InitializerValue;
2525 ConvertedValue = ConvertedValue.trunc(ToWidth);
2526 ConvertedValue.setIsSigned(ToSigned);
2527 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2528 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2529 // If the result is different, this was a narrowing conversion.
2530 return ConvertedValue != InitializerValue;
2531 } else {
2532 // Variables are always narrowings.
2533 *isInitializerConstant = false;
2534 return true;
2535 }
2536 }
2537 return false;
2538 }
2539
2540 default:
2541 // Other kinds of conversions are not narrowings.
2542 return false;
2543 }
2544}
2545
Douglas Gregor20093b42009-12-09 23:02:17 +00002546void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002547 FunctionDecl *Function,
2548 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 Step S;
2550 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2551 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002552 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002553 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002554 Steps.push_back(S);
2555}
2556
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002557void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002558 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002559 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002560 switch (VK) {
2561 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2562 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2563 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002564 default: llvm_unreachable("No such category");
2565 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002566 S.Type = BaseType;
2567 Steps.push_back(S);
2568}
2569
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002570void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002571 bool BindingTemporary) {
2572 Step S;
2573 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2574 S.Type = T;
2575 Steps.push_back(S);
2576}
2577
Douglas Gregor523d46a2010-04-18 07:40:54 +00002578void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2579 Step S;
2580 S.Kind = SK_ExtraneousCopyToTemporary;
2581 S.Type = T;
2582 Steps.push_back(S);
2583}
2584
Eli Friedman03981012009-12-11 02:42:07 +00002585void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002586 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002587 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002588 Step S;
2589 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002590 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002591 S.Function.Function = Function;
2592 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002593 Steps.push_back(S);
2594}
2595
2596void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002597 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002598 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002599 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002600 switch (VK) {
2601 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002602 S.Kind = SK_QualificationConversionRValue;
2603 break;
John McCall5baba9d2010-08-25 10:28:54 +00002604 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002605 S.Kind = SK_QualificationConversionXValue;
2606 break;
John McCall5baba9d2010-08-25 10:28:54 +00002607 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002608 S.Kind = SK_QualificationConversionLValue;
2609 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002610 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002611 S.Type = Ty;
2612 Steps.push_back(S);
2613}
2614
2615void InitializationSequence::AddConversionSequenceStep(
2616 const ImplicitConversionSequence &ICS,
2617 QualType T) {
2618 Step S;
2619 S.Kind = SK_ConversionSequence;
2620 S.Type = T;
2621 S.ICS = new ImplicitConversionSequence(ICS);
2622 Steps.push_back(S);
2623}
2624
Douglas Gregord87b61f2009-12-10 17:56:55 +00002625void InitializationSequence::AddListInitializationStep(QualType T) {
2626 Step S;
2627 S.Kind = SK_ListInitialization;
2628 S.Type = T;
2629 Steps.push_back(S);
2630}
2631
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002632void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002633InitializationSequence::AddConstructorInitializationStep(
2634 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002635 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002636 QualType T) {
2637 Step S;
2638 S.Kind = SK_ConstructorInitialization;
2639 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002640 S.Function.Function = Constructor;
2641 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002642 Steps.push_back(S);
2643}
2644
Douglas Gregor71d17402009-12-15 00:01:57 +00002645void InitializationSequence::AddZeroInitializationStep(QualType T) {
2646 Step S;
2647 S.Kind = SK_ZeroInitialization;
2648 S.Type = T;
2649 Steps.push_back(S);
2650}
2651
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002652void InitializationSequence::AddCAssignmentStep(QualType T) {
2653 Step S;
2654 S.Kind = SK_CAssignment;
2655 S.Type = T;
2656 Steps.push_back(S);
2657}
2658
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002659void InitializationSequence::AddStringInitStep(QualType T) {
2660 Step S;
2661 S.Kind = SK_StringInit;
2662 S.Type = T;
2663 Steps.push_back(S);
2664}
2665
Douglas Gregor569c3162010-08-07 11:51:51 +00002666void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2667 Step S;
2668 S.Kind = SK_ObjCObjectConversion;
2669 S.Type = T;
2670 Steps.push_back(S);
2671}
2672
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002673void InitializationSequence::AddArrayInitStep(QualType T) {
2674 Step S;
2675 S.Kind = SK_ArrayInit;
2676 S.Type = T;
2677 Steps.push_back(S);
2678}
2679
John McCallf85e1932011-06-15 23:02:42 +00002680void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2681 bool shouldCopy) {
2682 Step s;
2683 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2684 : SK_PassByIndirectRestore);
2685 s.Type = type;
2686 Steps.push_back(s);
2687}
2688
2689void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2690 Step S;
2691 S.Kind = SK_ProduceObjCObject;
2692 S.Type = T;
2693 Steps.push_back(S);
2694}
2695
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002696void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002697 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002698 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002699 this->Failure = Failure;
2700 this->FailedOverloadResult = Result;
2701}
2702
2703//===----------------------------------------------------------------------===//
2704// Attempt initialization
2705//===----------------------------------------------------------------------===//
2706
John McCallf85e1932011-06-15 23:02:42 +00002707static void MaybeProduceObjCObject(Sema &S,
2708 InitializationSequence &Sequence,
2709 const InitializedEntity &Entity) {
2710 if (!S.getLangOptions().ObjCAutoRefCount) return;
2711
2712 /// When initializing a parameter, produce the value if it's marked
2713 /// __attribute__((ns_consumed)).
2714 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2715 if (!Entity.isParameterConsumed())
2716 return;
2717
2718 assert(Entity.getType()->isObjCRetainableType() &&
2719 "consuming an object of unretainable type?");
2720 Sequence.AddProduceObjCObjectStep(Entity.getType());
2721
2722 /// When initializing a return value, if the return type is a
2723 /// retainable type, then returns need to immediately retain the
2724 /// object. If an autorelease is required, it will be done at the
2725 /// last instant.
2726 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2727 if (!Entity.getType()->isObjCRetainableType())
2728 return;
2729
2730 Sequence.AddProduceObjCObjectStep(Entity.getType());
2731 }
2732}
2733
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002734/// \brief Attempt list initialization (C++0x [dcl.init.list])
2735static void TryListInitialization(Sema &S,
2736 const InitializedEntity &Entity,
2737 const InitializationKind &Kind,
2738 InitListExpr *InitList,
2739 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002740 QualType DestType = Entity.getType();
2741
Sebastian Redl14b0c192011-09-24 17:48:00 +00002742 // C++ doesn't allow scalar initialization with more than one argument.
2743 // But C99 complex numbers are scalars and it makes sense there.
2744 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2745 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2746 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2747 return;
2748 }
2749 // FIXME: C++0x defines behavior for these two cases.
2750 if (DestType->isReferenceType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002751 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2752 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002753 }
2754 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002755 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002756 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002757 }
2758
Sebastian Redl14b0c192011-09-24 17:48:00 +00002759 InitListChecker CheckInitList(S, Entity, InitList,
2760 DestType, /*VerifyOnly=*/true);
2761 if (CheckInitList.HadError()) {
2762 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2763 return;
2764 }
2765
2766 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002767 Sequence.AddListInitializationStep(DestType);
2768}
Douglas Gregor20093b42009-12-09 23:02:17 +00002769
2770/// \brief Try a reference initialization that involves calling a conversion
2771/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002772static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2773 const InitializedEntity &Entity,
2774 const InitializationKind &Kind,
2775 Expr *Initializer,
2776 bool AllowRValues,
2777 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002778 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002779 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2780 QualType T1 = cv1T1.getUnqualifiedType();
2781 QualType cv2T2 = Initializer->getType();
2782 QualType T2 = cv2T2.getUnqualifiedType();
2783
2784 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002785 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002786 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002787 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002788 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002789 ObjCConversion,
2790 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002791 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002792 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002793 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002794 (void)ObjCLifetimeConversion;
2795
Douglas Gregor20093b42009-12-09 23:02:17 +00002796 // Build the candidate set directly in the initialization sequence
2797 // structure, so that it will persist if we fail.
2798 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2799 CandidateSet.clear();
2800
2801 // Determine whether we are allowed to call explicit constructors or
2802 // explicit conversion operators.
2803 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002804
Douglas Gregor20093b42009-12-09 23:02:17 +00002805 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002806 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2807 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002808 // The type we're converting to is a class type. Enumerate its constructors
2809 // to see if there is a suitable conversion.
2810 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002811
Douglas Gregor20093b42009-12-09 23:02:17 +00002812 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002813 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002814 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002815 NamedDecl *D = *Con;
2816 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2817
Douglas Gregor20093b42009-12-09 23:02:17 +00002818 // Find the constructor (which may be a template).
2819 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002820 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002821 if (ConstructorTmpl)
2822 Constructor = cast<CXXConstructorDecl>(
2823 ConstructorTmpl->getTemplatedDecl());
2824 else
John McCall9aa472c2010-03-19 07:35:19 +00002825 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002826
Douglas Gregor20093b42009-12-09 23:02:17 +00002827 if (!Constructor->isInvalidDecl() &&
2828 Constructor->isConvertingConstructor(AllowExplicit)) {
2829 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002830 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002831 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002832 &Initializer, 1, CandidateSet,
2833 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002834 else
John McCall9aa472c2010-03-19 07:35:19 +00002835 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002836 &Initializer, 1, CandidateSet,
2837 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002838 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002839 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002840 }
John McCall572fc622010-08-17 07:23:57 +00002841 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2842 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002843
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002844 const RecordType *T2RecordType = 0;
2845 if ((T2RecordType = T2->getAs<RecordType>()) &&
2846 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002847 // The type we're converting from is a class type, enumerate its conversion
2848 // functions.
2849 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2850
John McCalleec51cf2010-01-20 00:46:10 +00002851 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002852 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002853 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2854 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002855 NamedDecl *D = *I;
2856 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2857 if (isa<UsingShadowDecl>(D))
2858 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002859
Douglas Gregor20093b42009-12-09 23:02:17 +00002860 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2861 CXXConversionDecl *Conv;
2862 if (ConvTemplate)
2863 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2864 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002865 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002866
Douglas Gregor20093b42009-12-09 23:02:17 +00002867 // If the conversion function doesn't return a reference type,
2868 // it can't be considered for this conversion unless we're allowed to
2869 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002870 // FIXME: Do we need to make sure that we only consider conversion
2871 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002872 // break recursion.
2873 if ((AllowExplicit || !Conv->isExplicit()) &&
2874 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2875 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002876 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002877 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002878 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002879 else
John McCall9aa472c2010-03-19 07:35:19 +00002880 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002881 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002882 }
2883 }
2884 }
John McCall572fc622010-08-17 07:23:57 +00002885 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2886 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002887
Douglas Gregor20093b42009-12-09 23:02:17 +00002888 SourceLocation DeclLoc = Initializer->getLocStart();
2889
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002890 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002891 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002893 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002894 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002895
Douglas Gregor20093b42009-12-09 23:02:17 +00002896 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002897
Chandler Carruth25ca4212011-02-25 19:41:05 +00002898 // This is the overload that will actually be used for the initialization, so
2899 // mark it as used.
2900 S.MarkDeclarationReferenced(DeclLoc, Function);
2901
Eli Friedman03981012009-12-11 02:42:07 +00002902 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002903 if (isa<CXXConversionDecl>(Function))
2904 T2 = Function->getResultType();
2905 else
2906 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002907
2908 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002909 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002910 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002911
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002912 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002913 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002914 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002915 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002916 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002917 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002918 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002919
Douglas Gregor20093b42009-12-09 23:02:17 +00002920 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002921 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002922 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002923 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002924 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002925 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002926 NewDerivedToBase, NewObjCConversion,
2927 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002928 if (NewRefRelationship == Sema::Ref_Incompatible) {
2929 // If the type we've converted to is not reference-related to the
2930 // type we're looking for, then there is another conversion step
2931 // we need to perform to produce a temporary of the right type
2932 // that we'll be binding to.
2933 ImplicitConversionSequence ICS;
2934 ICS.setStandard();
2935 ICS.Standard = Best->FinalConversion;
2936 T2 = ICS.Standard.getToType(2);
2937 Sequence.AddConversionSequenceStep(ICS, T2);
2938 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002939 Sequence.AddDerivedToBaseCastStep(
2940 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002941 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002942 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002943 else if (NewObjCConversion)
2944 Sequence.AddObjCObjectConversionStep(
2945 S.Context.getQualifiedType(T1,
2946 T2.getNonReferenceType().getQualifiers()));
2947
Douglas Gregor20093b42009-12-09 23:02:17 +00002948 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002949 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950
Douglas Gregor20093b42009-12-09 23:02:17 +00002951 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2952 return OR_Success;
2953}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954
2955/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2956static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002957 const InitializedEntity &Entity,
2958 const InitializationKind &Kind,
2959 Expr *Initializer,
2960 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002961 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002962 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002963 Qualifiers T1Quals;
2964 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002965 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002966 Qualifiers T2Quals;
2967 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002968 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002969
Douglas Gregor20093b42009-12-09 23:02:17 +00002970 // If the initializer is the address of an overloaded function, try
2971 // to resolve the overloaded function. If all goes well, T2 is the
2972 // type of the resulting function.
2973 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002974 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002975 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002976 T1,
2977 false,
2978 Found)) {
2979 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2980 cv2T2 = Fn->getType();
2981 T2 = cv2T2.getUnqualifiedType();
2982 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002983 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2984 return;
2985 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002986 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002987
Douglas Gregor20093b42009-12-09 23:02:17 +00002988 // Compute some basic properties of the types and the initializer.
2989 bool isLValueRef = DestType->isLValueReferenceType();
2990 bool isRValueRef = !isLValueRef;
2991 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002992 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002993 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002994 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002995 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002996 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002997 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002998
Douglas Gregor20093b42009-12-09 23:02:17 +00002999 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003000 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003001 // "cv2 T2" as follows:
3002 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003003 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003004 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003005 // Note the analogous bullet points for rvlaue refs to functions. Because
3006 // there are no function rvalues in C++, rvalue refs to functions are treated
3007 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003008 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003009 bool T1Function = T1->isFunctionType();
3010 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003011 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003012 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003013 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003014 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003015 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003016 // reference-compatible with "cv2 T2," or
3017 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003018 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003019 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003020 // can occur. However, we do pay attention to whether it is a bit-field
3021 // to decide whether we're actually binding to a temporary created from
3022 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003023 if (DerivedToBase)
3024 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003025 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003026 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003027 else if (ObjCConversion)
3028 Sequence.AddObjCObjectConversionStep(
3029 S.Context.getQualifiedType(T1, T2Quals));
3030
Chandler Carruth5535c382010-01-12 20:32:25 +00003031 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003032 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003033 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003034 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003035 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003036 return;
3037 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003038
3039 // - has a class type (i.e., T2 is a class type), where T1 is not
3040 // reference-related to T2, and can be implicitly converted to an
3041 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3042 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003043 // applicable conversion functions (13.3.1.6) and choosing the best
3044 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003045 // If we have an rvalue ref to function type here, the rhs must be
3046 // an rvalue.
3047 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3048 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003050 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003051 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003052 Sequence);
3053 if (ConvOvlResult == OR_Success)
3054 return;
John McCall1d318332010-01-12 00:44:57 +00003055 if (ConvOvlResult != OR_No_Viable_Function) {
3056 Sequence.SetOverloadFailure(
3057 InitializationSequence::FK_ReferenceInitOverloadFailed,
3058 ConvOvlResult);
3059 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003060 }
3061 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003062
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003064 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003065 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003066 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003067 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3068 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3069 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003070 Sequence.SetOverloadFailure(
3071 InitializationSequence::FK_ReferenceInitOverloadFailed,
3072 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003073 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003074 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003075 ? (RefRelationship == Sema::Ref_Related
3076 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3077 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3078 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003079
Douglas Gregor20093b42009-12-09 23:02:17 +00003080 return;
3081 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003082
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003083 // - If the initializer expression
3084 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3085 // "cv1 T1" is reference-compatible with "cv2 T2"
3086 // Note: functions are handled below.
3087 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003088 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003089 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003090 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003091 (InitCategory.isXValue() ||
3092 (InitCategory.isPRValue() && T2->isRecordType()) ||
3093 (InitCategory.isPRValue() && T2->isArrayType()))) {
3094 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3095 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003096 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3097 // compiler the freedom to perform a copy here or bind to the
3098 // object, while C++0x requires that we bind directly to the
3099 // object. Hence, we always bind to the object without making an
3100 // extra copy. However, in C++03 requires that we check for the
3101 // presence of a suitable copy constructor:
3102 //
3103 // The constructor that would be used to make the copy shall
3104 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003105 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003106 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00003107 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003108
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003109 if (DerivedToBase)
3110 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3111 ValueKind);
3112 else if (ObjCConversion)
3113 Sequence.AddObjCObjectConversionStep(
3114 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003115
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003116 if (T1Quals != T2Quals)
3117 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003119 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122
3123 // - has a class type (i.e., T2 is a class type), where T1 is not
3124 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003125 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3126 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003127 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003128 if (RefRelationship == Sema::Ref_Incompatible) {
3129 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3130 Kind, Initializer,
3131 /*AllowRValues=*/true,
3132 Sequence);
3133 if (ConvOvlResult)
3134 Sequence.SetOverloadFailure(
3135 InitializationSequence::FK_ReferenceInitOverloadFailed,
3136 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137
Douglas Gregor20093b42009-12-09 23:02:17 +00003138 return;
3139 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
Douglas Gregor20093b42009-12-09 23:02:17 +00003141 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3142 return;
3143 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003144
3145 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003146 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003149
Douglas Gregor20093b42009-12-09 23:02:17 +00003150 // Determine whether we are allowed to call explicit constructors or
3151 // explicit conversion operators.
3152 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003153
3154 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3155
John McCallf85e1932011-06-15 23:02:42 +00003156 ImplicitConversionSequence ICS
3157 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003158 /*SuppressUserConversions*/ false,
3159 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003160 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003161 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3162 /*AllowObjCWritebackConversion=*/false);
3163
3164 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003165 // FIXME: Use the conversion function set stored in ICS to turn
3166 // this into an overloading ambiguity diagnostic. However, we need
3167 // to keep that set as an OverloadCandidateSet rather than as some
3168 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003169 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3170 Sequence.SetOverloadFailure(
3171 InitializationSequence::FK_ReferenceInitOverloadFailed,
3172 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003173 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3174 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003175 else
3176 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003177 return;
John McCallf85e1932011-06-15 23:02:42 +00003178 } else {
3179 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003180 }
3181
3182 // [...] If T1 is reference-related to T2, cv1 must be the
3183 // same cv-qualification as, or greater cv-qualification
3184 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003185 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3186 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003188 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003189 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3190 return;
3191 }
3192
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003194 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003196 InitCategory.isLValue()) {
3197 Sequence.SetFailed(
3198 InitializationSequence::FK_RValueReferenceBindingToLValue);
3199 return;
3200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201
Douglas Gregor20093b42009-12-09 23:02:17 +00003202 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3203 return;
3204}
3205
3206/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207/// (C++ [dcl.init.string], C99 6.7.8).
3208static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003209 const InitializedEntity &Entity,
3210 const InitializationKind &Kind,
3211 Expr *Initializer,
3212 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003213 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003214}
3215
Douglas Gregor20093b42009-12-09 23:02:17 +00003216/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3217/// enumerates the constructors of the initialized entity and performs overload
3218/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003220 const InitializedEntity &Entity,
3221 const InitializationKind &Kind,
3222 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003223 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003224 InitializationSequence &Sequence) {
Richard Trieu898267f2011-09-01 21:44:13 +00003225 // Check constructor arguments for self reference.
3226 if (DeclaratorDecl *DD = Entity.getDecl())
3227 // Parameters arguments are occassionially constructed with itself,
3228 // for instance, in recursive functions. Skip them.
3229 if (!isa<ParmVarDecl>(DD))
3230 for (unsigned i = 0; i < NumArgs; ++i)
3231 S.CheckSelfReference(DD, Args[i]);
3232
Douglas Gregor51c56d62009-12-14 20:49:26 +00003233 // Build the candidate set directly in the initialization sequence
3234 // structure, so that it will persist if we fail.
3235 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3236 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003237
Douglas Gregor51c56d62009-12-14 20:49:26 +00003238 // Determine whether we are allowed to call explicit constructors or
3239 // explicit conversion operators.
3240 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3241 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003242 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003243
3244 // The type we're constructing needs to be complete.
3245 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003246 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003247 return;
3248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003249
Douglas Gregor51c56d62009-12-14 20:49:26 +00003250 // The type we're converting to is a class type. Enumerate its constructors
3251 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003252 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003253 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003254 CXXRecordDecl *DestRecordDecl
3255 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256
Douglas Gregor51c56d62009-12-14 20:49:26 +00003257 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003258 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003259 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003260 NamedDecl *D = *Con;
3261 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003262 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263
Douglas Gregor51c56d62009-12-14 20:49:26 +00003264 // Find the constructor (which may be a template).
3265 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003266 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003267 if (ConstructorTmpl)
3268 Constructor = cast<CXXConstructorDecl>(
3269 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003270 else {
John McCall9aa472c2010-03-19 07:35:19 +00003271 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003272
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003274 // suppress user-defined conversions on the arguments.
3275 // FIXME: Move constructors?
3276 if (Kind.getKind() == InitializationKind::IK_Copy &&
3277 Constructor->isCopyConstructor())
3278 SuppressUserConversions = true;
3279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003280
Douglas Gregor51c56d62009-12-14 20:49:26 +00003281 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003282 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003283 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003284 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003285 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003286 Args, NumArgs, CandidateSet,
3287 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003288 else
John McCall9aa472c2010-03-19 07:35:19 +00003289 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003290 Args, NumArgs, CandidateSet,
3291 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003292 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003293 }
3294
Douglas Gregor51c56d62009-12-14 20:49:26 +00003295 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003296
3297 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003298 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003299 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003300 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003301 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003302 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003303 Result);
3304 return;
3305 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003306
3307 // C++0x [dcl.init]p6:
3308 // If a program calls for the default initialization of an object
3309 // of a const-qualified type T, T shall be a class type with a
3310 // user-provided default constructor.
3311 if (Kind.getKind() == InitializationKind::IK_Default &&
3312 Entity.getType().isConstQualified() &&
3313 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3314 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3315 return;
3316 }
3317
Douglas Gregor51c56d62009-12-14 20:49:26 +00003318 // Add the constructor initialization step. Any cv-qualification conversion is
3319 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003320 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003321 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003322 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003323 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003324}
3325
Douglas Gregor71d17402009-12-15 00:01:57 +00003326/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003328 const InitializedEntity &Entity,
3329 const InitializationKind &Kind,
3330 InitializationSequence &Sequence) {
3331 // C++ [dcl.init]p5:
3332 //
3333 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003334 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335
Douglas Gregor71d17402009-12-15 00:01:57 +00003336 // -- if T is an array type, then each element is value-initialized;
3337 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3338 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339
Douglas Gregor71d17402009-12-15 00:01:57 +00003340 if (const RecordType *RT = T->getAs<RecordType>()) {
3341 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3342 // -- if T is a class type (clause 9) with a user-declared
3343 // constructor (12.1), then the default constructor for T is
3344 // called (and the initialization is ill-formed if T has no
3345 // accessible default constructor);
3346 //
3347 // FIXME: we really want to refer to a single subobject of the array,
3348 // but Entity doesn't have a way to capture that (yet).
3349 if (ClassDecl->hasUserDeclaredConstructor())
3350 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003351
Douglas Gregor16006c92009-12-16 18:50:27 +00003352 // -- if T is a (possibly cv-qualified) non-union class type
3353 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003354 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003355 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003356 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003357 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003358 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003359 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003360 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003361 }
3362 }
3363
Douglas Gregord6542d82009-12-22 15:35:07 +00003364 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003365}
3366
Douglas Gregor99a2e602009-12-16 01:38:02 +00003367/// \brief Attempt default initialization (C++ [dcl.init]p6).
3368static void TryDefaultInitialization(Sema &S,
3369 const InitializedEntity &Entity,
3370 const InitializationKind &Kind,
3371 InitializationSequence &Sequence) {
3372 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373
Douglas Gregor99a2e602009-12-16 01:38:02 +00003374 // C++ [dcl.init]p6:
3375 // To default-initialize an object of type T means:
3376 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003377 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3378
Douglas Gregor99a2e602009-12-16 01:38:02 +00003379 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3380 // constructor for T is called (and the initialization is ill-formed if
3381 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003382 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003383 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3384 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003385 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386
Douglas Gregor99a2e602009-12-16 01:38:02 +00003387 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregor99a2e602009-12-16 01:38:02 +00003389 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003391 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003392 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003393 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003394 return;
3395 }
3396
3397 // If the destination type has a lifetime property, zero-initialize it.
3398 if (DestType.getQualifiers().hasObjCLifetime()) {
3399 Sequence.AddZeroInitializationStep(Entity.getType());
3400 return;
3401 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003402}
3403
Douglas Gregor20093b42009-12-09 23:02:17 +00003404/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3405/// which enumerates all conversion functions and performs overload resolution
3406/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003408 const InitializedEntity &Entity,
3409 const InitializationKind &Kind,
3410 Expr *Initializer,
3411 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003412 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003413 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3414 QualType SourceType = Initializer->getType();
3415 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3416 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003417
Douglas Gregor4a520a22009-12-14 17:27:33 +00003418 // Build the candidate set directly in the initialization sequence
3419 // structure, so that it will persist if we fail.
3420 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3421 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
Douglas Gregor4a520a22009-12-14 17:27:33 +00003423 // Determine whether we are allowed to call explicit constructors or
3424 // explicit conversion operators.
3425 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003426
Douglas Gregor4a520a22009-12-14 17:27:33 +00003427 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3428 // The type we're converting to is a class type. Enumerate its constructors
3429 // to see if there is a suitable conversion.
3430 CXXRecordDecl *DestRecordDecl
3431 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003432
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003433 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003434 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003435 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003436 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003437 Con != ConEnd; ++Con) {
3438 NamedDecl *D = *Con;
3439 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003441 // Find the constructor (which may be a template).
3442 CXXConstructorDecl *Constructor = 0;
3443 FunctionTemplateDecl *ConstructorTmpl
3444 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003445 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003446 Constructor = cast<CXXConstructorDecl>(
3447 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003448 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003449 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003450
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003451 if (!Constructor->isInvalidDecl() &&
3452 Constructor->isConvertingConstructor(AllowExplicit)) {
3453 if (ConstructorTmpl)
3454 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3455 /*ExplicitArgs*/ 0,
3456 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003457 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003458 else
3459 S.AddOverloadCandidate(Constructor, FoundDecl,
3460 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003461 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003462 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003463 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003464 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003465 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003466
3467 SourceLocation DeclLoc = Initializer->getLocStart();
3468
Douglas Gregor4a520a22009-12-14 17:27:33 +00003469 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3470 // The type we're converting from is a class type, enumerate its conversion
3471 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003472
Eli Friedman33c2da92009-12-20 22:12:03 +00003473 // We can only enumerate the conversion functions for a complete type; if
3474 // the type isn't complete, simply skip this step.
3475 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3476 CXXRecordDecl *SourceRecordDecl
3477 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478
John McCalleec51cf2010-01-20 00:46:10 +00003479 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003480 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003481 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003482 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003483 I != E; ++I) {
3484 NamedDecl *D = *I;
3485 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3486 if (isa<UsingShadowDecl>(D))
3487 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488
Eli Friedman33c2da92009-12-20 22:12:03 +00003489 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3490 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003491 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003492 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003493 else
John McCall32daa422010-03-31 01:36:47 +00003494 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003495
Eli Friedman33c2da92009-12-20 22:12:03 +00003496 if (AllowExplicit || !Conv->isExplicit()) {
3497 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003498 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003499 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003500 CandidateSet);
3501 else
John McCall9aa472c2010-03-19 07:35:19 +00003502 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003503 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003504 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003505 }
3506 }
3507 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003508
3509 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003510 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003511 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003512 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003513 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003515 Result);
3516 return;
3517 }
John McCall1d318332010-01-12 00:44:57 +00003518
Douglas Gregor4a520a22009-12-14 17:27:33 +00003519 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003520 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521
Douglas Gregor4a520a22009-12-14 17:27:33 +00003522 if (isa<CXXConstructorDecl>(Function)) {
3523 // Add the user-defined conversion step. Any cv-qualification conversion is
3524 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003525 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003526 return;
3527 }
3528
3529 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003530 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003531 if (ConvType->getAs<RecordType>()) {
3532 // If we're converting to a class type, there may be an copy if
3533 // the resulting temporary object (possible to create an object of
3534 // a base class type). That copy is not a separate conversion, so
3535 // we just make a note of the actual destination type (possibly a
3536 // base class of the type returned by the conversion function) and
3537 // let the user-defined conversion step handle the conversion.
3538 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3539 return;
3540 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003541
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003542 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003543
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003544 // If the conversion following the call to the conversion function
3545 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003546 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3547 Best->FinalConversion.Third) {
3548 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003549 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003550 ICS.Standard = Best->FinalConversion;
3551 Sequence.AddConversionSequenceStep(ICS, DestType);
3552 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003553}
3554
John McCallf85e1932011-06-15 23:02:42 +00003555/// The non-zero enum values here are indexes into diagnostic alternatives.
3556enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3557
3558/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003559static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3560 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003561 // Skip parens.
3562 e = e->IgnoreParens();
3563
3564 // Skip address-of nodes.
3565 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3566 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003567 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003568
3569 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003570 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3571 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003572 case CK_Dependent:
3573 case CK_BitCast:
3574 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003575 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003576 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003577
3578 case CK_ArrayToPointerDecay:
3579 return IIK_nonscalar;
3580
3581 case CK_NullToPointer:
3582 return IIK_okay;
3583
3584 default:
3585 break;
3586 }
3587
3588 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003589 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3590 if (!isAddressOf) return IIK_nonlocal;
3591
3592 VarDecl *var;
3593 if (isa<DeclRefExpr>(e)) {
3594 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3595 if (!var) return IIK_nonlocal;
3596 } else {
3597 var = cast<BlockDeclRefExpr>(e)->getDecl();
3598 }
3599
3600 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003601
3602 // If we have a conditional operator, check both sides.
3603 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003604 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003605 return iik;
3606
John McCallc03fa492011-06-27 23:59:58 +00003607 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003608
3609 // These are never scalar.
3610 } else if (isa<ArraySubscriptExpr>(e)) {
3611 return IIK_nonscalar;
3612
3613 // Otherwise, it needs to be a null pointer constant.
3614 } else {
3615 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3616 ? IIK_okay : IIK_nonlocal);
3617 }
3618
3619 return IIK_nonlocal;
3620}
3621
3622/// Check whether the given expression is a valid operand for an
3623/// indirect copy/restore.
3624static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3625 assert(src->isRValue());
3626
John McCallc03fa492011-06-27 23:59:58 +00003627 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003628 if (iik == IIK_okay) return;
3629
3630 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3631 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3632 << src->getSourceRange();
3633}
3634
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003635/// \brief Determine whether we have compatible array types for the
3636/// purposes of GNU by-copy array initialization.
3637static bool hasCompatibleArrayTypes(ASTContext &Context,
3638 const ArrayType *Dest,
3639 const ArrayType *Source) {
3640 // If the source and destination array types are equivalent, we're
3641 // done.
3642 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3643 return true;
3644
3645 // Make sure that the element types are the same.
3646 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3647 return false;
3648
3649 // The only mismatch we allow is when the destination is an
3650 // incomplete array type and the source is a constant array type.
3651 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3652}
3653
John McCallf85e1932011-06-15 23:02:42 +00003654static bool tryObjCWritebackConversion(Sema &S,
3655 InitializationSequence &Sequence,
3656 const InitializedEntity &Entity,
3657 Expr *Initializer) {
3658 bool ArrayDecay = false;
3659 QualType ArgType = Initializer->getType();
3660 QualType ArgPointee;
3661 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3662 ArrayDecay = true;
3663 ArgPointee = ArgArrayType->getElementType();
3664 ArgType = S.Context.getPointerType(ArgPointee);
3665 }
3666
3667 // Handle write-back conversion.
3668 QualType ConvertedArgType;
3669 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3670 ConvertedArgType))
3671 return false;
3672
3673 // We should copy unless we're passing to an argument explicitly
3674 // marked 'out'.
3675 bool ShouldCopy = true;
3676 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3677 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3678
3679 // Do we need an lvalue conversion?
3680 if (ArrayDecay || Initializer->isGLValue()) {
3681 ImplicitConversionSequence ICS;
3682 ICS.setStandard();
3683 ICS.Standard.setAsIdentityConversion();
3684
3685 QualType ResultType;
3686 if (ArrayDecay) {
3687 ICS.Standard.First = ICK_Array_To_Pointer;
3688 ResultType = S.Context.getPointerType(ArgPointee);
3689 } else {
3690 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3691 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3692 }
3693
3694 Sequence.AddConversionSequenceStep(ICS, ResultType);
3695 }
3696
3697 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3698 return true;
3699}
3700
Douglas Gregor20093b42009-12-09 23:02:17 +00003701InitializationSequence::InitializationSequence(Sema &S,
3702 const InitializedEntity &Entity,
3703 const InitializationKind &Kind,
3704 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003705 unsigned NumArgs)
3706 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003707 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Douglas Gregor20093b42009-12-09 23:02:17 +00003709 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710 // The semantics of initializers are as follows. The destination type is
3711 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003712 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003713 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003714 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003715 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003716
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003717 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003718 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3719 SequenceKind = DependentSequence;
3720 return;
3721 }
3722
Sebastian Redl7491c492011-06-05 13:59:11 +00003723 // Almost everything is a normal sequence.
3724 setSequenceKind(NormalSequence);
3725
John McCall241d5582010-12-07 22:54:16 +00003726 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003727 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3728 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3729 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003730 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003731 return;
3732 }
3733 Args[I] = Result.take();
3734 }
John McCall241d5582010-12-07 22:54:16 +00003735
Douglas Gregor20093b42009-12-09 23:02:17 +00003736 QualType SourceType;
3737 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003738 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003739 Initializer = Args[0];
3740 if (!isa<InitListExpr>(Initializer))
3741 SourceType = Initializer->getType();
3742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743
3744 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003745 // list-initialized (8.5.4).
3746 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003747 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003748 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750
Douglas Gregor20093b42009-12-09 23:02:17 +00003751 // - If the destination type is a reference type, see 8.5.3.
3752 if (DestType->isReferenceType()) {
3753 // C++0x [dcl.init.ref]p1:
3754 // A variable declared to be a T& or T&&, that is, "reference to type T"
3755 // (8.3.2), shall be initialized by an object, or function, of type T or
3756 // by an object that can be converted into a T.
3757 // (Therefore, multiple arguments are not permitted.)
3758 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003759 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003760 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003761 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003762 return;
3763 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003764
Douglas Gregor20093b42009-12-09 23:02:17 +00003765 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003766 if (Kind.getKind() == InitializationKind::IK_Value ||
3767 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003768 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003769 return;
3770 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003771
Douglas Gregor99a2e602009-12-16 01:38:02 +00003772 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003773 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003774 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003775 return;
3776 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003777
John McCallce6c9b72011-02-21 07:22:22 +00003778 // - If the destination type is an array of characters, an array of
3779 // char16_t, an array of char32_t, or an array of wchar_t, and the
3780 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003781 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003782 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003783 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3784 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003785 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003786 return;
3787 }
3788
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003789 // Note: as an GNU C extension, we allow initialization of an
3790 // array from a compound literal that creates an array of the same
3791 // type, so long as the initializer has no side effects.
3792 if (!S.getLangOptions().CPlusPlus && Initializer &&
3793 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3794 Initializer->getType()->isArrayType()) {
3795 const ArrayType *SourceAT
3796 = Context.getAsArrayType(Initializer->getType());
3797 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003798 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003799 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003800 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003801 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003802 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003803 }
3804 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003805 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003806 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003807 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808
Douglas Gregor20093b42009-12-09 23:02:17 +00003809 return;
3810 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003811
John McCallf85e1932011-06-15 23:02:42 +00003812 // Determine whether we should consider writeback conversions for
3813 // Objective-C ARC.
3814 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3815 Entity.getKind() == InitializedEntity::EK_Parameter;
3816
3817 // We're at the end of the line for C: it's either a write-back conversion
3818 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003819 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003820 // If allowed, check whether this is an Objective-C writeback conversion.
3821 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003822 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003823 return;
3824 }
3825
3826 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003827 AddCAssignmentStep(DestType);
3828 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003829 return;
3830 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831
John McCallf85e1932011-06-15 23:02:42 +00003832 assert(S.getLangOptions().CPlusPlus);
3833
Douglas Gregor20093b42009-12-09 23:02:17 +00003834 // - If the destination type is a (possibly cv-qualified) class type:
3835 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836 // - If the initialization is direct-initialization, or if it is
3837 // copy-initialization where the cv-unqualified version of the
3838 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003839 // class of the destination, constructors are considered. [...]
3840 if (Kind.getKind() == InitializationKind::IK_Direct ||
3841 (Kind.getKind() == InitializationKind::IK_Copy &&
3842 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3843 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003845 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003847 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003849 // used) to a derived class thereof are enumerated as described in
3850 // 13.3.1.4, and the best one is chosen through overload resolution
3851 // (13.3).
3852 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003853 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003854 return;
3855 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003856
Douglas Gregor99a2e602009-12-16 01:38:02 +00003857 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003858 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003859 return;
3860 }
3861 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862
3863 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003864 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003865 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003866 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3867 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003868 return;
3869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003870
Douglas Gregor20093b42009-12-09 23:02:17 +00003871 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003872 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003873 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003874 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003875 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003876
3877 ImplicitConversionSequence ICS
3878 = S.TryImplicitConversion(Initializer, Entity.getType(),
3879 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003880 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003881 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003882 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3883 allowObjCWritebackConversion);
3884
3885 if (ICS.isStandard() &&
3886 ICS.Standard.Second == ICK_Writeback_Conversion) {
3887 // Objective-C ARC writeback conversion.
3888
3889 // We should copy unless we're passing to an argument explicitly
3890 // marked 'out'.
3891 bool ShouldCopy = true;
3892 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3893 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3894
3895 // If there was an lvalue adjustment, add it as a separate conversion.
3896 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3897 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3898 ImplicitConversionSequence LvalueICS;
3899 LvalueICS.setStandard();
3900 LvalueICS.Standard.setAsIdentityConversion();
3901 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3902 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003903 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003904 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003905
3906 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003907 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003908 DeclAccessPair dap;
3909 if (Initializer->getType() == Context.OverloadTy &&
3910 !S.ResolveAddressOfOverloadedFunction(Initializer
3911 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003912 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003913 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003914 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003915 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003916 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003917
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003918 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003919 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003920}
3921
3922InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003923 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003924 StepEnd = Steps.end();
3925 Step != StepEnd; ++Step)
3926 Step->Destroy();
3927}
3928
3929//===----------------------------------------------------------------------===//
3930// Perform initialization
3931//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003932static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003933getAssignmentAction(const InitializedEntity &Entity) {
3934 switch(Entity.getKind()) {
3935 case InitializedEntity::EK_Variable:
3936 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003937 case InitializedEntity::EK_Exception:
3938 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003939 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003940 return Sema::AA_Initializing;
3941
3942 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003943 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003944 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3945 return Sema::AA_Sending;
3946
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003947 return Sema::AA_Passing;
3948
3949 case InitializedEntity::EK_Result:
3950 return Sema::AA_Returning;
3951
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003952 case InitializedEntity::EK_Temporary:
3953 // FIXME: Can we tell apart casting vs. converting?
3954 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003955
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003956 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003957 case InitializedEntity::EK_ArrayElement:
3958 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003959 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003960 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003961 return Sema::AA_Initializing;
3962 }
3963
3964 return Sema::AA_Converting;
3965}
3966
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003967/// \brief Whether we should binding a created object as a temporary when
3968/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003969static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003970 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003971 case InitializedEntity::EK_ArrayElement:
3972 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003973 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003974 case InitializedEntity::EK_New:
3975 case InitializedEntity::EK_Variable:
3976 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003977 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003978 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003979 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003980 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003981 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003982 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003984 case InitializedEntity::EK_Parameter:
3985 case InitializedEntity::EK_Temporary:
3986 return true;
3987 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003989 llvm_unreachable("missed an InitializedEntity kind?");
3990}
3991
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003992/// \brief Whether the given entity, when initialized with an object
3993/// created for that initialization, requires destruction.
3994static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3995 switch (Entity.getKind()) {
3996 case InitializedEntity::EK_Member:
3997 case InitializedEntity::EK_Result:
3998 case InitializedEntity::EK_New:
3999 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004000 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004001 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004002 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004003 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004004 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004006 case InitializedEntity::EK_Variable:
4007 case InitializedEntity::EK_Parameter:
4008 case InitializedEntity::EK_Temporary:
4009 case InitializedEntity::EK_ArrayElement:
4010 case InitializedEntity::EK_Exception:
4011 return true;
4012 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004013
4014 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004015}
4016
Douglas Gregor523d46a2010-04-18 07:40:54 +00004017/// \brief Make a (potentially elidable) temporary copy of the object
4018/// provided by the given initializer by calling the appropriate copy
4019/// constructor.
4020///
4021/// \param S The Sema object used for type-checking.
4022///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004023/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004024/// the type of the initializer expression or a superclass thereof.
4025///
4026/// \param Enter The entity being initialized.
4027///
4028/// \param CurInit The initializer expression.
4029///
4030/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4031/// is permitted in C++03 (but not C++0x) when binding a reference to
4032/// an rvalue.
4033///
4034/// \returns An expression that copies the initializer expression into
4035/// a temporary object, or an error expression if a copy could not be
4036/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004037static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004038 QualType T,
4039 const InitializedEntity &Entity,
4040 ExprResult CurInit,
4041 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004042 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004043 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004045 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004046 Class = cast<CXXRecordDecl>(Record->getDecl());
4047 if (!Class)
4048 return move(CurInit);
4049
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004050 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004051 // When certain criteria are met, an implementation is allowed to
4052 // omit the copy/move construction of a class object, even if the
4053 // copy/move constructor and/or destructor for the object have
4054 // side effects. [...]
4055 // - when a temporary class object that has not been bound to a
4056 // reference (12.2) would be copied/moved to a class object
4057 // with the same cv-unqualified type, the copy/move operation
4058 // can be omitted by constructing the temporary object
4059 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004060 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004061 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004062 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004064 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004065 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004066 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004067 switch (Entity.getKind()) {
4068 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004069 Loc = Entity.getReturnLoc();
4070 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004071
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004072 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004073 Loc = Entity.getThrowLoc();
4074 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004076 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004077 Loc = Entity.getDecl()->getLocation();
4078 break;
4079
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004080 case InitializedEntity::EK_ArrayElement:
4081 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004082 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004083 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00004084 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004085 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004086 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004087 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004088 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004089 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00004090 Loc = CurInitExpr->getLocStart();
4091 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004092 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004093
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004095 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4096 return move(CurInit);
4097
Douglas Gregorcc15f012011-01-21 19:38:21 +00004098 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004099 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00004100 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00004101 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004102 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004103 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004104 // C++0x [dcl.init]p16, second bullet to class types, this
4105 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004106 CXXConstructorDecl *Constructor = 0;
4107
4108 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004109 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004110 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00004111 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004112 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004113 continue;
4114
4115 DeclAccessPair FoundDecl
4116 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4117 S.AddOverloadCandidate(Constructor, FoundDecl,
4118 &CurInitExpr, 1, CandidateSet);
4119 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004120 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00004121
4122 // Handle constructor templates.
4123 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4124 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004125 continue;
John McCall9aa472c2010-03-19 07:35:19 +00004126
Douglas Gregor6493cc52010-11-08 17:16:59 +00004127 Constructor = cast<CXXConstructorDecl>(
4128 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004129 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004130 continue;
4131
4132 // FIXME: Do we need to limit this to copy-constructor-like
4133 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00004134 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00004135 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4136 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4137 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00004138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004139
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004140 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004141 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004142 case OR_Success:
4143 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004145 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004146 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4147 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4148 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004149 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004150 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004151 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004152 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004153 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004154 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004155
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004156 case OR_Ambiguous:
4157 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004158 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004159 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004160 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004161 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004162
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004163 case OR_Deleted:
4164 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004165 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004166 << CurInitExpr->getSourceRange();
4167 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004168 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004169 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004170 }
4171
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004172 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004173 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004174 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004175
Anders Carlsson9a68a672010-04-21 18:47:17 +00004176 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004177 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004178
4179 if (IsExtraneousCopy) {
4180 // If this is a totally extraneous copy for C++03 reference
4181 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004182 // expression. We don't generate an (elided) copy operation here
4183 // because doing so would require us to pass down a flag to avoid
4184 // infinite recursion, where each step adds another extraneous,
4185 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004186
Douglas Gregor2559a702010-04-18 07:57:34 +00004187 // Instantiate the default arguments of any extra parameters in
4188 // the selected copy constructor, as if we were going to create a
4189 // proper call to the copy constructor.
4190 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4191 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4192 if (S.RequireCompleteType(Loc, Parm->getType(),
4193 S.PDiag(diag::err_call_incomplete_argument)))
4194 break;
4195
4196 // Build the default argument expression; we don't actually care
4197 // if this succeeds or not, because this routine will complain
4198 // if there was a problem.
4199 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4200 }
4201
Douglas Gregor523d46a2010-04-18 07:40:54 +00004202 return S.Owned(CurInitExpr);
4203 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204
Chandler Carruth25ca4212011-02-25 19:41:05 +00004205 S.MarkDeclarationReferenced(Loc, Constructor);
4206
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004207 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004208 // constructor call (we might have derived-to-base conversions, or
4209 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004210 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004211 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004212 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004213
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004214 // Actually perform the constructor call.
4215 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004216 move_arg(ConstructorArgs),
4217 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004218 CXXConstructExpr::CK_Complete,
4219 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004220
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004221 // If we're supposed to bind temporaries, do so.
4222 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4223 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4224 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004225}
Douglas Gregor20093b42009-12-09 23:02:17 +00004226
Douglas Gregora41a8c52010-04-22 00:20:18 +00004227void InitializationSequence::PrintInitLocationNote(Sema &S,
4228 const InitializedEntity &Entity) {
4229 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4230 if (Entity.getDecl()->getLocation().isInvalid())
4231 return;
4232
4233 if (Entity.getDecl()->getDeclName())
4234 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4235 << Entity.getDecl()->getDeclName();
4236 else
4237 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4238 }
4239}
4240
Sebastian Redl3b802322011-07-14 19:07:55 +00004241static bool isReferenceBinding(const InitializationSequence::Step &s) {
4242 return s.Kind == InitializationSequence::SK_BindReference ||
4243 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4244}
4245
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004247InitializationSequence::Perform(Sema &S,
4248 const InitializedEntity &Entity,
4249 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004250 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004251 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004252 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004253 unsigned NumArgs = Args.size();
4254 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004255 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004257
Sebastian Redl7491c492011-06-05 13:59:11 +00004258 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004259 // If the declaration is a non-dependent, incomplete array type
4260 // that has an initializer, then its type will be completed once
4261 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004262 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004263 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004264 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004265 if (const IncompleteArrayType *ArrayT
4266 = S.Context.getAsIncompleteArrayType(DeclType)) {
4267 // FIXME: We don't currently have the ability to accurately
4268 // compute the length of an initializer list without
4269 // performing full type-checking of the initializer list
4270 // (since we have to determine where braces are implicitly
4271 // introduced and such). So, we fall back to making the array
4272 // type a dependently-sized array type with no specified
4273 // bound.
4274 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4275 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004276
Douglas Gregord87b61f2009-12-10 17:56:55 +00004277 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004278 if (DeclaratorDecl *DD = Entity.getDecl()) {
4279 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4280 TypeLoc TL = TInfo->getTypeLoc();
4281 if (IncompleteArrayTypeLoc *ArrayLoc
4282 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4283 Brackets = ArrayLoc->getBracketsRange();
4284 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004285 }
4286
4287 *ResultType
4288 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4289 /*NumElts=*/0,
4290 ArrayT->getSizeModifier(),
4291 ArrayT->getIndexTypeCVRQualifiers(),
4292 Brackets);
4293 }
4294
4295 }
4296 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004297 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4298 Kind.isExplicitCast());
4299 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004300 }
4301
Sebastian Redl7491c492011-06-05 13:59:11 +00004302 // No steps means no initialization.
4303 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004304 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305
Douglas Gregord6542d82009-12-22 15:35:07 +00004306 QualType DestType = Entity.getType().getNonReferenceType();
4307 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004308 // the same as Entity.getDecl()->getType() in cases involving type merging,
4309 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004310 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004311 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004312 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004313
John McCall60d7b3a2010-08-24 06:29:42 +00004314 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004317 // grab the only argument out the Args and place it into the "current"
4318 // initializer.
4319 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004320 case SK_ResolveAddressOfOverloadedFunction:
4321 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004322 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004323 case SK_CastDerivedToBaseLValue:
4324 case SK_BindReference:
4325 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004326 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004327 case SK_UserConversion:
4328 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004329 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004330 case SK_QualificationConversionRValue:
4331 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004332 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004333 case SK_ListInitialization:
4334 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004335 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004336 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004337 case SK_ArrayInit:
4338 case SK_PassByIndirectCopyRestore:
4339 case SK_PassByIndirectRestore:
4340 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004341 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004342 CurInit = Args.get()[0];
4343 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004344
4345 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004346 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4347 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4348 if (CurInit.isInvalid())
4349 return ExprError();
4350 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004351 break;
John McCallf6a16482010-12-04 03:47:34 +00004352 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004353
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004354 case SK_ConstructorInitialization:
4355 case SK_ZeroInitialization:
4356 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358
4359 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004360 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004361 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004362 for (step_iterator Step = step_begin(), StepEnd = step_end();
4363 Step != StepEnd; ++Step) {
4364 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004365 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004366
John Wiegley429bb272011-04-08 18:41:53 +00004367 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004368
Douglas Gregor20093b42009-12-09 23:02:17 +00004369 switch (Step->Kind) {
4370 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004371 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004372 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004373 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004374 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004375 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004376 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004377 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004378 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004379
Douglas Gregor20093b42009-12-09 23:02:17 +00004380 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004381 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004382 case SK_CastDerivedToBaseLValue: {
4383 // We have a derived-to-base cast that produces either an rvalue or an
4384 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004385
John McCallf871d0c2010-08-07 06:22:56 +00004386 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004387
Douglas Gregor20093b42009-12-09 23:02:17 +00004388 // Casts to inaccessible base classes are allowed with C-style casts.
4389 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4390 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004391 CurInit.get()->getLocStart(),
4392 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004393 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004394 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004395
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004396 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4397 QualType T = SourceType;
4398 if (const PointerType *Pointer = T->getAs<PointerType>())
4399 T = Pointer->getPointeeType();
4400 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004401 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004402 cast<CXXRecordDecl>(RecordTy->getDecl()));
4403 }
4404
John McCall5baba9d2010-08-25 10:28:54 +00004405 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004406 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004407 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004408 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004409 VK_XValue :
4410 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004411 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4412 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004413 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004414 CurInit.get(),
4415 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004416 break;
4417 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004418
Douglas Gregor20093b42009-12-09 23:02:17 +00004419 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004420 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004421 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4422 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004423 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004424 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004425 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004426 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004427 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004428 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004429
John Wiegley429bb272011-04-08 18:41:53 +00004430 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004431 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004432 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4433 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004434 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004435 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004436 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004437 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004438
Douglas Gregor20093b42009-12-09 23:02:17 +00004439 // Reference binding does not have any corresponding ASTs.
4440
4441 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004442 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004443 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004444
Douglas Gregor20093b42009-12-09 23:02:17 +00004445 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004446
Douglas Gregor20093b42009-12-09 23:02:17 +00004447 case SK_BindReferenceToTemporary:
4448 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004449 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004450 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004451
Douglas Gregor03e80032011-06-21 17:03:29 +00004452 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004453 CurInit = new (S.Context) MaterializeTemporaryExpr(
4454 Entity.getType().getNonReferenceType(),
4455 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004456 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004457
4458 // If we're binding to an Objective-C object that has lifetime, we
4459 // need cleanups.
4460 if (S.getLangOptions().ObjCAutoRefCount &&
4461 CurInit.get()->getType()->isObjCLifetimeType())
4462 S.ExprNeedsCleanups = true;
4463
Douglas Gregor20093b42009-12-09 23:02:17 +00004464 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004465
Douglas Gregor523d46a2010-04-18 07:40:54 +00004466 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004468 /*IsExtraneousCopy=*/true);
4469 break;
4470
Douglas Gregor20093b42009-12-09 23:02:17 +00004471 case SK_UserConversion: {
4472 // We have a user-defined conversion that invokes either a constructor
4473 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004474 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004475 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004476 FunctionDecl *Fn = Step->Function.Function;
4477 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004478 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004479 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004480 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004481 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004482 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004483 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004484 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004485
Douglas Gregor20093b42009-12-09 23:02:17 +00004486 // Determine the arguments required to actually perform the constructor
4487 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004488 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004489 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004490 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004491 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004492 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004493
Douglas Gregor20093b42009-12-09 23:02:17 +00004494 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004496 move_arg(ConstructorArgs),
4497 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004498 CXXConstructExpr::CK_Complete,
4499 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004500 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004501 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004502
Anders Carlsson9a68a672010-04-21 18:47:17 +00004503 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004504 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004505 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004506
John McCall2de56d12010-08-25 11:45:40 +00004507 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004508 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4509 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4510 S.IsDerivedFrom(SourceType, Class))
4511 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004513 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004514 } else {
4515 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004516 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004517 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004518 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004519 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004520 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521
4522 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004523 // derived-to-base conversion? I believe the answer is "no", because
4524 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004525 ExprResult CurInitExprRes =
4526 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4527 FoundFn, Conversion);
4528 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004529 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004530 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531
Douglas Gregor20093b42009-12-09 23:02:17 +00004532 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004533 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004534 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004535 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004536
John McCall2de56d12010-08-25 11:45:40 +00004537 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004539 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004540 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004541
Sebastian Redl3b802322011-07-14 19:07:55 +00004542 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004543 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004544 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004545 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004546 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004547 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004549 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004550 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004551 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004552 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4553 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004554 }
4555 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004556
Sebastian Redl906082e2010-07-20 04:20:21 +00004557 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004558 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004559 CurInit.get()->getType(),
4560 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004561 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004562
Douglas Gregor2f599792010-04-02 18:24:57 +00004563 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004564 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4565 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004566
Douglas Gregor20093b42009-12-09 23:02:17 +00004567 break;
4568 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004569
Douglas Gregor20093b42009-12-09 23:02:17 +00004570 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004571 case SK_QualificationConversionXValue:
4572 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004573 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004574 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004575 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004576 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004577 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004578 VK_XValue :
4579 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004580 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004581 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004582 }
4583
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004584 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004585 Sema::CheckedConversionKind CCK
4586 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4587 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4588 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4589 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004590 ExprResult CurInitExprRes =
4591 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004592 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004593 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004594 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004595 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004596 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004598
Douglas Gregord87b61f2009-12-10 17:56:55 +00004599 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004600 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004601 QualType Ty = Step->Type;
Sebastian Redl14b0c192011-09-24 17:48:00 +00004602 InitListChecker PerformInitList(S, Entity, InitList,
4603 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4604 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00004605 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004606
4607 CurInit.release();
Sebastian Redl14b0c192011-09-24 17:48:00 +00004608 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004609 break;
4610 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004611
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004612 case SK_ListConstructorCall:
4613 assert(false && "List constructor calls not yet supported.");
4614
Douglas Gregor51c56d62009-12-14 20:49:26 +00004615 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004616 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004617 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004618 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619
Douglas Gregor51c56d62009-12-14 20:49:26 +00004620 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004621 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004622 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4623 ? Kind.getEqualLoc()
4624 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004625
4626 if (Kind.getKind() == InitializationKind::IK_Default) {
4627 // Force even a trivial, implicit default constructor to be
4628 // semantically checked. We do this explicitly because we don't build
4629 // the definition for completely trivial constructors.
4630 CXXRecordDecl *ClassDecl = Constructor->getParent();
4631 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004632 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004633 ClassDecl->hasTrivialDefaultConstructor() &&
4634 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004635 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4636 }
4637
Douglas Gregor51c56d62009-12-14 20:49:26 +00004638 // Determine the arguments required to actually perform the constructor
4639 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004641 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004642 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004643
4644
Douglas Gregor91be6f52010-03-02 17:18:33 +00004645 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004646 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004647 (Kind.getKind() == InitializationKind::IK_Direct ||
4648 Kind.getKind() == InitializationKind::IK_Value)) {
4649 // An explicitly-constructed temporary, e.g., X(1, 2).
4650 unsigned NumExprs = ConstructorArgs.size();
4651 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004652 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004653 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004654
Douglas Gregorab6677e2010-09-08 00:15:04 +00004655 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4656 if (!TSInfo)
4657 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658
Douglas Gregor91be6f52010-03-02 17:18:33 +00004659 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4660 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004661 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004663 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004664 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004665 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004666 } else {
4667 CXXConstructExpr::ConstructionKind ConstructKind =
4668 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004669
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004670 if (Entity.getKind() == InitializedEntity::EK_Base) {
4671 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004672 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004673 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004674 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004675 ConstructKind = CXXConstructExpr::CK_Delegating;
4676 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677
Chandler Carruth428edaf2010-10-25 08:47:36 +00004678 // Only get the parenthesis range if it is a direct construction.
4679 SourceRange parenRange =
4680 Kind.getKind() == InitializationKind::IK_Direct ?
4681 Kind.getParenRange() : SourceRange();
4682
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004683 // If the entity allows NRVO, mark the construction as elidable
4684 // unconditionally.
4685 if (Entity.allowsNRVO())
4686 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4687 Constructor, /*Elidable=*/true,
4688 move_arg(ConstructorArgs),
4689 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004690 ConstructKind,
4691 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004692 else
4693 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004694 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004695 move_arg(ConstructorArgs),
4696 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004697 ConstructKind,
4698 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004699 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004700 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004701 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004702
4703 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004704 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004705 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004706 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004707
Douglas Gregor2f599792010-04-02 18:24:57 +00004708 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004709 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004710
Douglas Gregor51c56d62009-12-14 20:49:26 +00004711 break;
4712 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004713
Douglas Gregor71d17402009-12-15 00:01:57 +00004714 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004715 step_iterator NextStep = Step;
4716 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004718 NextStep->Kind == SK_ConstructorInitialization) {
4719 // The need for zero-initialization is recorded directly into
4720 // the call to the object's constructor within the next step.
4721 ConstructorInitRequiresZeroInit = true;
4722 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4723 S.getLangOptions().CPlusPlus &&
4724 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004725 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4726 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004727 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004728 Kind.getRange().getBegin());
4729
4730 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4731 TSInfo->getType().getNonLValueExprType(S.Context),
4732 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004733 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004734 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004735 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004736 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004737 break;
4738 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004739
4740 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004741 QualType SourceType = CurInit.get()->getType();
4742 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004743 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004744 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4745 if (Result.isInvalid())
4746 return ExprError();
4747 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004748
4749 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004750 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004751 if (ConvTy != Sema::Compatible &&
4752 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004753 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004754 == Sema::Compatible)
4755 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004756 if (CurInitExprRes.isInvalid())
4757 return ExprError();
4758 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004759
Douglas Gregora41a8c52010-04-22 00:20:18 +00004760 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004761 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4762 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004763 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004764 getAssignmentAction(Entity),
4765 &Complained)) {
4766 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004767 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004768 } else if (Complained)
4769 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004770 break;
4771 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004772
4773 case SK_StringInit: {
4774 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004775 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004776 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004777 break;
4778 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004779
4780 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004781 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004782 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004783 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004784 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004785
4786 case SK_ArrayInit:
4787 // Okay: we checked everything before creating this step. Note that
4788 // this is a GNU extension.
4789 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004790 << Step->Type << CurInit.get()->getType()
4791 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004792
4793 // If the destination type is an incomplete array type, update the
4794 // type accordingly.
4795 if (ResultType) {
4796 if (const IncompleteArrayType *IncompleteDest
4797 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4798 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004799 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004800 *ResultType = S.Context.getConstantArrayType(
4801 IncompleteDest->getElementType(),
4802 ConstantSource->getSize(),
4803 ArrayType::Normal, 0);
4804 }
4805 }
4806 }
John McCallf85e1932011-06-15 23:02:42 +00004807 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004808
John McCallf85e1932011-06-15 23:02:42 +00004809 case SK_PassByIndirectCopyRestore:
4810 case SK_PassByIndirectRestore:
4811 checkIndirectCopyRestoreSource(S, CurInit.get());
4812 CurInit = S.Owned(new (S.Context)
4813 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4814 Step->Kind == SK_PassByIndirectCopyRestore));
4815 break;
4816
4817 case SK_ProduceObjCObject:
4818 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00004819 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00004820 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004821 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004822 }
4823 }
John McCall15d7d122010-11-11 03:21:53 +00004824
4825 // Diagnose non-fatal problems with the completed initialization.
4826 if (Entity.getKind() == InitializedEntity::EK_Member &&
4827 cast<FieldDecl>(Entity.getDecl())->isBitField())
4828 S.CheckBitFieldInitialization(Kind.getLocation(),
4829 cast<FieldDecl>(Entity.getDecl()),
4830 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004831
Douglas Gregor20093b42009-12-09 23:02:17 +00004832 return move(CurInit);
4833}
4834
4835//===----------------------------------------------------------------------===//
4836// Diagnose initialization failures
4837//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004838bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004839 const InitializedEntity &Entity,
4840 const InitializationKind &Kind,
4841 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004842 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004843 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004844
Douglas Gregord6542d82009-12-22 15:35:07 +00004845 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004846 switch (Failure) {
4847 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004848 // FIXME: Customize for the initialized entity?
4849 if (NumArgs == 0)
4850 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4851 << DestType.getNonReferenceType();
4852 else // FIXME: diagnostic below could be better!
4853 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4854 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004855 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004856
Douglas Gregor20093b42009-12-09 23:02:17 +00004857 case FK_ArrayNeedsInitList:
4858 case FK_ArrayNeedsInitListOrStringLiteral:
4859 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4860 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4861 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004862
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004863 case FK_ArrayTypeMismatch:
4864 case FK_NonConstantArrayInit:
4865 S.Diag(Kind.getLocation(),
4866 (Failure == FK_ArrayTypeMismatch
4867 ? diag::err_array_init_different_type
4868 : diag::err_array_init_non_constant_array))
4869 << DestType.getNonReferenceType()
4870 << Args[0]->getType()
4871 << Args[0]->getSourceRange();
4872 break;
4873
John McCall6bb80172010-03-30 21:47:33 +00004874 case FK_AddressOfOverloadFailed: {
4875 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004876 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004877 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004878 true,
4879 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004880 break;
John McCall6bb80172010-03-30 21:47:33 +00004881 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004882
Douglas Gregor20093b42009-12-09 23:02:17 +00004883 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004884 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004885 switch (FailedOverloadResult) {
4886 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004887 if (Failure == FK_UserConversionOverloadFailed)
4888 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4889 << Args[0]->getType() << DestType
4890 << Args[0]->getSourceRange();
4891 else
4892 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4893 << DestType << Args[0]->getType()
4894 << Args[0]->getSourceRange();
4895
John McCall120d63c2010-08-24 20:38:10 +00004896 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004897 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004898
Douglas Gregor20093b42009-12-09 23:02:17 +00004899 case OR_No_Viable_Function:
4900 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4901 << Args[0]->getType() << DestType.getNonReferenceType()
4902 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004903 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004904 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004905
Douglas Gregor20093b42009-12-09 23:02:17 +00004906 case OR_Deleted: {
4907 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4908 << Args[0]->getType() << DestType.getNonReferenceType()
4909 << Args[0]->getSourceRange();
4910 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004911 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004912 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4913 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004914 if (Ovl == OR_Deleted) {
4915 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004916 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004917 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004918 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004919 }
4920 break;
4921 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004922
Douglas Gregor20093b42009-12-09 23:02:17 +00004923 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004924 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004925 break;
4926 }
4927 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004928
Douglas Gregor20093b42009-12-09 23:02:17 +00004929 case FK_NonConstLValueReferenceBindingToTemporary:
4930 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004931 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004932 Failure == FK_NonConstLValueReferenceBindingToTemporary
4933 ? diag::err_lvalue_reference_bind_to_temporary
4934 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004935 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004936 << DestType.getNonReferenceType()
4937 << Args[0]->getType()
4938 << Args[0]->getSourceRange();
4939 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004940
Douglas Gregor20093b42009-12-09 23:02:17 +00004941 case FK_RValueReferenceBindingToLValue:
4942 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004943 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004944 << Args[0]->getSourceRange();
4945 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004946
Douglas Gregor20093b42009-12-09 23:02:17 +00004947 case FK_ReferenceInitDropsQualifiers:
4948 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4949 << DestType.getNonReferenceType()
4950 << Args[0]->getType()
4951 << Args[0]->getSourceRange();
4952 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004953
Douglas Gregor20093b42009-12-09 23:02:17 +00004954 case FK_ReferenceInitFailed:
4955 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4956 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004957 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004958 << Args[0]->getType()
4959 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004960 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4961 Args[0]->getType()->isObjCObjectPointerType())
4962 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004963 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004964
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004965 case FK_ConversionFailed: {
4966 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004967 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4968 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004969 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004970 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004971 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004972 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004973 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4974 Args[0]->getType()->isObjCObjectPointerType())
4975 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004976 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004977 }
John Wiegley429bb272011-04-08 18:41:53 +00004978
4979 case FK_ConversionFromPropertyFailed:
4980 // No-op. This error has already been reported.
4981 break;
4982
Douglas Gregord87b61f2009-12-10 17:56:55 +00004983 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004984 SourceRange R;
4985
4986 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004987 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004988 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004989 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004990 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004991
Douglas Gregor19311e72010-09-08 21:40:08 +00004992 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4993 if (Kind.isCStyleOrFunctionalCast())
4994 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4995 << R;
4996 else
4997 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4998 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004999 break;
5000 }
5001
5002 case FK_ReferenceBindingToInitList:
5003 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5004 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5005 break;
5006
5007 case FK_InitListBadDestinationType:
5008 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5009 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5010 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005011
Douglas Gregor51c56d62009-12-14 20:49:26 +00005012 case FK_ConstructorOverloadFailed: {
5013 SourceRange ArgsRange;
5014 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005016 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005017
Douglas Gregor51c56d62009-12-14 20:49:26 +00005018 // FIXME: Using "DestType" for the entity we're printing is probably
5019 // bad.
5020 switch (FailedOverloadResult) {
5021 case OR_Ambiguous:
5022 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5023 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005024 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5025 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005026 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005027
Douglas Gregor51c56d62009-12-14 20:49:26 +00005028 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005029 if (Kind.getKind() == InitializationKind::IK_Default &&
5030 (Entity.getKind() == InitializedEntity::EK_Base ||
5031 Entity.getKind() == InitializedEntity::EK_Member) &&
5032 isa<CXXConstructorDecl>(S.CurContext)) {
5033 // This is implicit default initialization of a member or
5034 // base within a constructor. If no viable function was
5035 // found, notify the user that she needs to explicitly
5036 // initialize this base/member.
5037 CXXConstructorDecl *Constructor
5038 = cast<CXXConstructorDecl>(S.CurContext);
5039 if (Entity.getKind() == InitializedEntity::EK_Base) {
5040 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5041 << Constructor->isImplicit()
5042 << S.Context.getTypeDeclType(Constructor->getParent())
5043 << /*base=*/0
5044 << Entity.getType();
5045
5046 RecordDecl *BaseDecl
5047 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5048 ->getDecl();
5049 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5050 << S.Context.getTagDeclType(BaseDecl);
5051 } else {
5052 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5053 << Constructor->isImplicit()
5054 << S.Context.getTypeDeclType(Constructor->getParent())
5055 << /*member=*/1
5056 << Entity.getName();
5057 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5058
5059 if (const RecordType *Record
5060 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005061 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005062 diag::note_previous_decl)
5063 << S.Context.getTagDeclType(Record->getDecl());
5064 }
5065 break;
5066 }
5067
Douglas Gregor51c56d62009-12-14 20:49:26 +00005068 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5069 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005070 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005071 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005072
Douglas Gregor51c56d62009-12-14 20:49:26 +00005073 case OR_Deleted: {
5074 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5075 << true << DestType << ArgsRange;
5076 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005077 OverloadingResult Ovl
5078 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005079 if (Ovl == OR_Deleted) {
5080 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005081 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005082 } else {
5083 llvm_unreachable("Inconsistent overload resolution?");
5084 }
5085 break;
5086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087
Douglas Gregor51c56d62009-12-14 20:49:26 +00005088 case OR_Success:
5089 llvm_unreachable("Conversion did not fail!");
5090 break;
5091 }
5092 break;
5093 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094
Douglas Gregor99a2e602009-12-16 01:38:02 +00005095 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005096 if (Entity.getKind() == InitializedEntity::EK_Member &&
5097 isa<CXXConstructorDecl>(S.CurContext)) {
5098 // This is implicit default-initialization of a const member in
5099 // a constructor. Complain that it needs to be explicitly
5100 // initialized.
5101 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5102 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5103 << Constructor->isImplicit()
5104 << S.Context.getTypeDeclType(Constructor->getParent())
5105 << /*const=*/1
5106 << Entity.getName();
5107 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5108 << Entity.getName();
5109 } else {
5110 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5111 << DestType << (bool)DestType->getAs<RecordType>();
5112 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005113 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005114
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005115 case FK_Incomplete:
5116 S.RequireCompleteType(Kind.getLocation(), DestType,
5117 diag::err_init_incomplete_type);
5118 break;
5119
Sebastian Redl14b0c192011-09-24 17:48:00 +00005120 case FK_ListInitializationFailed: {
5121 // Run the init list checker again to emit diagnostics.
5122 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5123 QualType DestType = Entity.getType();
5124 InitListChecker DiagnoseInitList(S, Entity, InitList,
5125 DestType, /*VerifyOnly=*/false);
5126 assert(DiagnoseInitList.HadError() &&
5127 "Inconsistent init list check result.");
5128 break;
5129 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005131
Douglas Gregora41a8c52010-04-22 00:20:18 +00005132 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005133 return true;
5134}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005135
Chris Lattner5f9e2722011-07-23 10:55:15 +00005136void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005137 switch (SequenceKind) {
5138 case FailedSequence: {
5139 OS << "Failed sequence: ";
5140 switch (Failure) {
5141 case FK_TooManyInitsForReference:
5142 OS << "too many initializers for reference";
5143 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005144
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005145 case FK_ArrayNeedsInitList:
5146 OS << "array requires initializer list";
5147 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005148
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005149 case FK_ArrayNeedsInitListOrStringLiteral:
5150 OS << "array requires initializer list or string literal";
5151 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005152
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005153 case FK_ArrayTypeMismatch:
5154 OS << "array type mismatch";
5155 break;
5156
5157 case FK_NonConstantArrayInit:
5158 OS << "non-constant array initializer";
5159 break;
5160
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005161 case FK_AddressOfOverloadFailed:
5162 OS << "address of overloaded function failed";
5163 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005164
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005165 case FK_ReferenceInitOverloadFailed:
5166 OS << "overload resolution for reference initialization failed";
5167 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005168
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005169 case FK_NonConstLValueReferenceBindingToTemporary:
5170 OS << "non-const lvalue reference bound to temporary";
5171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005172
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005173 case FK_NonConstLValueReferenceBindingToUnrelated:
5174 OS << "non-const lvalue reference bound to unrelated type";
5175 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005176
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005177 case FK_RValueReferenceBindingToLValue:
5178 OS << "rvalue reference bound to an lvalue";
5179 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005180
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005181 case FK_ReferenceInitDropsQualifiers:
5182 OS << "reference initialization drops qualifiers";
5183 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005184
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005185 case FK_ReferenceInitFailed:
5186 OS << "reference initialization failed";
5187 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005188
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005189 case FK_ConversionFailed:
5190 OS << "conversion failed";
5191 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005192
John Wiegley429bb272011-04-08 18:41:53 +00005193 case FK_ConversionFromPropertyFailed:
5194 OS << "conversion from property failed";
5195 break;
5196
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005197 case FK_TooManyInitsForScalar:
5198 OS << "too many initializers for scalar";
5199 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005200
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005201 case FK_ReferenceBindingToInitList:
5202 OS << "referencing binding to initializer list";
5203 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005204
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005205 case FK_InitListBadDestinationType:
5206 OS << "initializer list for non-aggregate, non-scalar type";
5207 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005208
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005209 case FK_UserConversionOverloadFailed:
5210 OS << "overloading failed for user-defined conversion";
5211 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005212
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005213 case FK_ConstructorOverloadFailed:
5214 OS << "constructor overloading failed";
5215 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005216
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005217 case FK_DefaultInitOfConst:
5218 OS << "default initialization of a const variable";
5219 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005220
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005221 case FK_Incomplete:
5222 OS << "initialization of incomplete type";
5223 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005224
5225 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005226 OS << "list initialization checker failure";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005227 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005228 OS << '\n';
5229 return;
5230 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005231
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005232 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005233 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005234 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005235
Sebastian Redl7491c492011-06-05 13:59:11 +00005236 case NormalSequence:
5237 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005238 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005239 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005241 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5242 if (S != step_begin()) {
5243 OS << " -> ";
5244 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005246 switch (S->Kind) {
5247 case SK_ResolveAddressOfOverloadedFunction:
5248 OS << "resolve address of overloaded function";
5249 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005250
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005251 case SK_CastDerivedToBaseRValue:
5252 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5253 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005254
Sebastian Redl906082e2010-07-20 04:20:21 +00005255 case SK_CastDerivedToBaseXValue:
5256 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5257 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005259 case SK_CastDerivedToBaseLValue:
5260 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5261 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005263 case SK_BindReference:
5264 OS << "bind reference to lvalue";
5265 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005267 case SK_BindReferenceToTemporary:
5268 OS << "bind reference to a temporary";
5269 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Douglas Gregor523d46a2010-04-18 07:40:54 +00005271 case SK_ExtraneousCopyToTemporary:
5272 OS << "extraneous C++03 copy to temporary";
5273 break;
5274
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005275 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005276 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005277 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005278
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005279 case SK_QualificationConversionRValue:
5280 OS << "qualification conversion (rvalue)";
5281
Sebastian Redl906082e2010-07-20 04:20:21 +00005282 case SK_QualificationConversionXValue:
5283 OS << "qualification conversion (xvalue)";
5284
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005285 case SK_QualificationConversionLValue:
5286 OS << "qualification conversion (lvalue)";
5287 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005288
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005289 case SK_ConversionSequence:
5290 OS << "implicit conversion sequence (";
5291 S->ICS->DebugPrint(); // FIXME: use OS
5292 OS << ")";
5293 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005294
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005295 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005296 OS << "list aggregate initialization";
5297 break;
5298
5299 case SK_ListConstructorCall:
5300 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005301 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005302
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005303 case SK_ConstructorInitialization:
5304 OS << "constructor initialization";
5305 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005306
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005307 case SK_ZeroInitialization:
5308 OS << "zero initialization";
5309 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005310
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005311 case SK_CAssignment:
5312 OS << "C assignment";
5313 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005314
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005315 case SK_StringInit:
5316 OS << "string initialization";
5317 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005318
5319 case SK_ObjCObjectConversion:
5320 OS << "Objective-C object conversion";
5321 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005322
5323 case SK_ArrayInit:
5324 OS << "array initialization";
5325 break;
John McCallf85e1932011-06-15 23:02:42 +00005326
5327 case SK_PassByIndirectCopyRestore:
5328 OS << "pass by indirect copy and restore";
5329 break;
5330
5331 case SK_PassByIndirectRestore:
5332 OS << "pass by indirect restore";
5333 break;
5334
5335 case SK_ProduceObjCObject:
5336 OS << "Objective-C object retension";
5337 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005338 }
5339 }
5340}
5341
5342void InitializationSequence::dump() const {
5343 dump(llvm::errs());
5344}
5345
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005346static void DiagnoseNarrowingInInitList(
5347 Sema& S, QualType EntityType, const Expr *InitE,
5348 bool Constant, const APValue &ConstantValue) {
5349 if (Constant) {
5350 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005351 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005352 ? diag::err_init_list_constant_narrowing
5353 : diag::warn_init_list_constant_narrowing)
5354 << InitE->getSourceRange()
5355 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005356 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005357 } else
5358 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005359 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005360 ? diag::err_init_list_variable_narrowing
5361 : diag::warn_init_list_variable_narrowing)
5362 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005363 << InitE->getType().getLocalUnqualifiedType()
5364 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005365
5366 llvm::SmallString<128> StaticCast;
5367 llvm::raw_svector_ostream OS(StaticCast);
5368 OS << "static_cast<";
5369 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5370 // It's important to use the typedef's name if there is one so that the
5371 // fixit doesn't break code using types like int64_t.
5372 //
5373 // FIXME: This will break if the typedef requires qualification. But
5374 // getQualifiedNameAsString() includes non-machine-parsable components.
5375 OS << TT->getDecl();
5376 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5377 OS << BT->getName(S.getLangOptions());
5378 else {
5379 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5380 // with a broken cast.
5381 return;
5382 }
5383 OS << ">(";
5384 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5385 << InitE->getSourceRange()
5386 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5387 << FixItHint::CreateInsertion(
5388 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5389}
5390
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005391//===----------------------------------------------------------------------===//
5392// Initialization helper functions
5393//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005394bool
5395Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5396 ExprResult Init) {
5397 if (Init.isInvalid())
5398 return false;
5399
5400 Expr *InitE = Init.get();
5401 assert(InitE && "No initialization expression");
5402
5403 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5404 SourceLocation());
5405 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005406 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005407}
5408
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005409ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005410Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5411 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005412 ExprResult Init,
5413 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005414 if (Init.isInvalid())
5415 return ExprError();
5416
John McCall15d7d122010-11-11 03:21:53 +00005417 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005418 assert(InitE && "No initialization expression?");
5419
5420 if (EqualLoc.isInvalid())
5421 EqualLoc = InitE->getLocStart();
5422
5423 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5424 EqualLoc);
5425 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5426 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005427
5428 bool Constant = false;
5429 APValue Result;
5430 if (TopLevelOfInitList &&
5431 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5432 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5433 Constant, Result);
5434 }
John McCallf312b1e2010-08-26 23:41:50 +00005435 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005436}