blob: cef4870638f9ca66de28577e6705351f13e3670b [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000026#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000027using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000028
Chris Lattner0cb78032009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCall66884dd2011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattnera9196812009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000040
Chris Lattnera9196812009-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 Lattner012b3392009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-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 Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-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 Lattnera9196812009-02-26 23:26:43 +000069
Douglas Gregorfb65e592011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump11289f42009-09-09 15:08:12 +000072
Douglas Gregorfb65e592011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000074}
75
John McCall66884dd2011-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 McCall5decec92011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattnerd8b741c82009-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 Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner0cb78032009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000099 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000100 }
Mike Stump11289f42009-09-09 15:08:12 +0000101
Eli Friedman893abe42009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman554eba92011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman893abe42009-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 Friedman554eba92011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-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 Friedman554eba92011-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 Stump11289f42009-09-09 15:08:12 +0000129
Eli Friedman893abe42009-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 Lattner0cb78032009-02-24 22:27:37 +0000135}
136
Chris Lattner0cb78032009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregorcde232f2009-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 Bagnara92141d22011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-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 Lattner9ececce2009-02-24 22:48:58 +0000168namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000175
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000177 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000179 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000180 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000185 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000186 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000187 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000192 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000193 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-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 Carlsson6cabf312010-01-23 23:23:01 +0000202 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000203 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000204 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000207 void CheckReferenceType(const InitializedEntity &Entity,
208 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000209 unsigned &Index,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000212 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000213 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000216 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000217 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000218 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000220 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000221 unsigned &StructuredIndex,
222 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000223 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000224 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000225 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000229 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000230 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000231 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000232 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 RecordDecl::field_iterator *NextField,
234 llvm::APSInt *NextElementIndex,
235 unsigned &Index,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000238 bool FinishSubobjectInit,
239 bool TopLevelObject);
Douglas Gregor85df8d82009-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 Gregorcde232f2009-01-29 01:05:33 +0000245 void UpdateStructuredListElement(InitListExpr *StructuredList,
246 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000247 Expr *expr);
248 int numArrayElements(QualType DeclType);
249 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000250
Douglas Gregor2bb07652009-12-22 00:05:34 +0000251 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
253 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000254 void FillInValueInitializations(const InitializedEntity &Entity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000256 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257 Expr *InitExpr, FieldDecl *Field,
258 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000259 void CheckValueInitializable(const InitializedEntity &Entity);
260
Douglas Gregor85df8d82009-01-29 00:45:39 +0000261public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000262 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000263 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264 bool HadError() { return hadError; }
265
266 // @brief Retrieves the fully-structured initializer list used for
267 // semantic analysis and code generation.
268 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
269};
Chris Lattner9ececce2009-02-24 22:48:58 +0000270} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000271
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000272void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
273 assert(VerifyOnly &&
274 "CheckValueInitializable is only inteded for verification mode.");
275
276 SourceLocation Loc;
277 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
278 true);
279 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
280 if (InitSeq.Failed())
281 hadError = true;
282}
283
Douglas Gregor2bb07652009-12-22 00:05:34 +0000284void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
285 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000287 bool &RequiresSecondPass) {
288 SourceLocation Loc = ILE->getSourceRange().getBegin();
289 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 = InitializedEntity::InitializeMember(Field, &ParentEntity);
292 if (Init >= NumInits || !ILE->getInit(Init)) {
293 // FIXME: We probably don't need to handle references
294 // specially here, since value-initialization of references is
295 // handled in InitializationSequence.
296 if (Field->getType()->isReferenceType()) {
297 // C++ [dcl.init.aggr]p9:
298 // If an incomplete or empty initializer-list leaves a
299 // member of reference type uninitialized, the program is
300 // ill-formed.
301 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
302 << Field->getType()
303 << ILE->getSyntacticForm()->getSourceRange();
304 SemaRef.Diag(Field->getLocation(),
305 diag::note_uninit_reference_member);
306 hadError = true;
307 return;
308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
Douglas Gregor2bb07652009-12-22 00:05:34 +0000310 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
311 true);
312 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
313 if (!InitSeq) {
314 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
315 hadError = true;
316 return;
317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000318
John McCalldadc5752010-08-24 06:29:42 +0000319 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000320 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 if (MemberInit.isInvalid()) {
322 hadError = true;
323 return;
324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000325
Douglas Gregor2bb07652009-12-22 00:05:34 +0000326 if (hadError) {
327 // Do nothing
328 } else if (Init < NumInits) {
329 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000330 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000331 // Value-initialization requires a constructor call, so
332 // extend the initializer list to include the constructor
333 // call and make a note that we'll need to take another pass
334 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000335 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000336 RequiresSecondPass = true;
337 }
338 } else if (InitListExpr *InnerILE
339 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000340 FillInValueInitializations(MemberEntity, InnerILE,
341 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000342}
343
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000344/// Recursively replaces NULL values within the given initializer list
345/// with expressions that perform value-initialization of the
346/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000347void
Douglas Gregor723796a2009-12-16 06:35:08 +0000348InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
349 InitListExpr *ILE,
350 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000351 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000352 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000353 SourceLocation Loc = ILE->getSourceRange().getBegin();
354 if (ILE->getSyntacticForm())
355 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000356
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000357 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000358 if (RType->getDecl()->isUnion() &&
359 ILE->getInitializedFieldInUnion())
360 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
361 Entity, ILE, RequiresSecondPass);
362 else {
363 unsigned Init = 0;
364 for (RecordDecl::field_iterator
365 Field = RType->getDecl()->field_begin(),
366 FieldEnd = RType->getDecl()->field_end();
367 Field != FieldEnd; ++Field) {
368 if (Field->isUnnamedBitfield())
369 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000370
Douglas Gregor2bb07652009-12-22 00:05:34 +0000371 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000373
374 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
375 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000377
Douglas Gregor2bb07652009-12-22 00:05:34 +0000378 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000379
Douglas Gregor2bb07652009-12-22 00:05:34 +0000380 // Only look at the first initialization of a union.
381 if (RType->getDecl()->isUnion())
382 break;
383 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000384 }
385
386 return;
Mike Stump11289f42009-09-09 15:08:12 +0000387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388
389 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000390
Douglas Gregor723796a2009-12-16 06:35:08 +0000391 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000392 unsigned NumInits = ILE->getNumInits();
393 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000394 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000395 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
397 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000400 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000401 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000402 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000403 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000404 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000405 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000406 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000407
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000409 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000410 if (hadError)
411 return;
412
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000413 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
414 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000415 ElementEntity.setElementIndex(Init);
416
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000417 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
419 true);
420 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
421 if (!InitSeq) {
422 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000423 hadError = true;
424 return;
425 }
426
John McCalldadc5752010-08-24 06:29:42 +0000427 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000428 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000429 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000430 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000431 return;
432 }
433
434 if (hadError) {
435 // Do nothing
436 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000437 // For arrays, just set the expression used for value-initialization
438 // of the "holes" in the array.
439 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
440 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
441 else
442 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000443 } else {
444 // For arrays, just set the expression used for value-initialization
445 // of the rest of elements and exit.
446 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
447 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
448 return;
449 }
450
Sebastian Redld201edf2011-06-05 13:59:11 +0000451 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000452 // Value-initialization requires a constructor call, so
453 // extend the initializer list to include the constructor
454 // call and make a note that we'll need to take another pass
455 // through the initializer list.
456 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
457 RequiresSecondPass = true;
458 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000459 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000460 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000461 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
462 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000463 }
464}
465
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000466
Douglas Gregor723796a2009-12-16 06:35:08 +0000467InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000468 InitListExpr *IL, QualType &T,
469 bool VerifyOnly)
470 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000471 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000472
Eli Friedman23a9e312008-05-19 19:16:24 +0000473 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000474 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000475 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000476 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000478 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000479 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000480
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000481 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000482 bool RequiresSecondPass = false;
483 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000484 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000486 RequiresSecondPass);
487 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000488}
489
490int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000491 // FIXME: use a proper constant
492 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000493 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000494 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000495 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
496 }
497 return maxElements;
498}
499
500int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000501 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000502 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000503 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000504 Field = structDecl->field_begin(),
505 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000506 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000507 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000508 ++InitializableMembers;
509 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000510 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000511 return std::min(InitializableMembers, 1);
512 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000513}
514
Anders Carlsson6cabf312010-01-23 23:23:01 +0000515void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000516 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000517 QualType T, unsigned &Index,
518 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000519 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000520 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000521
Steve Narofff8ecff22008-05-01 22:18:59 +0000522 if (T->isArrayType())
523 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000524 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000526 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000527 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000528 else
David Blaikie83d382b2011-09-23 05:06:16 +0000529 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000530
Eli Friedmane0f832b2008-05-25 13:49:22 +0000531 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000532 if (!VerifyOnly)
533 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
534 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000535 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000536 hadError = true;
537 return;
538 }
539
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 // Build a structured initializer list corresponding to this subobject.
541 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000542 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
543 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000544 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
545 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000546 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000547
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000548 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000549 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000551 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000552 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000553 StructuredSubobjectInitIndex);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000555 if (!VerifyOnly) {
556 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000557
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000558 // Update the structured sub-object initializer so that it's ending
559 // range corresponds with the end of the last initializer it used.
560 if (EndIndex < ParentIList->getNumInits()) {
561 SourceLocation EndLoc
562 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
563 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000566 // Warn about missing braces.
567 if (T->isArrayType() || T->isRecordType()) {
568 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
569 diag::warn_missing_braces)
570 << StructuredSubobjectInitList->getSourceRange()
571 << FixItHint::CreateInsertion(
572 StructuredSubobjectInitList->getLocStart(), "{")
573 << FixItHint::CreateInsertion(
574 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000576 "}");
577 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000578 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000579}
580
Anders Carlsson6cabf312010-01-23 23:23:01 +0000581void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000582 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000583 unsigned &Index,
584 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000585 unsigned &StructuredIndex,
586 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000588 if (!VerifyOnly) {
589 SyntacticToSemantic[IList] = StructuredList;
590 StructuredList->setSyntacticForm(IList);
591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000593 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000594 if (!VerifyOnly) {
595 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
596 IList->setType(ExprTy);
597 StructuredList->setType(ExprTy);
598 }
Eli Friedman85f54972008-05-25 13:22:35 +0000599 if (hadError)
600 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000601
Eli Friedman85f54972008-05-25 13:22:35 +0000602 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000603 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000604 if (VerifyOnly) {
605 if (SemaRef.getLangOptions().CPlusPlus ||
606 (SemaRef.getLangOptions().OpenCL &&
607 IList->getType()->isVectorType())) {
608 hadError = true;
609 }
610 return;
611 }
612
Eli Friedmanbd327452009-05-29 20:20:05 +0000613 if (StructuredIndex == 1 &&
614 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000615 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000616 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000617 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000618 hadError = true;
619 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000620 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000622 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000623 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000624 // Don't complain for incomplete types, since we'll get an error
625 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000626 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000627 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000628 CurrentObjectType->isArrayType()? 0 :
629 CurrentObjectType->isVectorType()? 1 :
630 CurrentObjectType->isScalarType()? 2 :
631 CurrentObjectType->isUnionType()? 3 :
632 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000633
634 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000635 if (SemaRef.getLangOptions().CPlusPlus) {
636 DK = diag::err_excess_initializers;
637 hadError = true;
638 }
Nate Begeman425038c2009-07-07 21:53:06 +0000639 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
640 DK = diag::err_excess_initializers;
641 hadError = true;
642 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000643
Chris Lattnerb0912a52009-02-24 22:50:46 +0000644 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000645 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000646 }
647 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000648
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000649 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
650 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000651 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000652 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000653 << FixItHint::CreateRemoval(IList->getLocStart())
654 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000655}
656
Anders Carlsson6cabf312010-01-23 23:23:01 +0000657void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000658 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000659 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000660 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000661 unsigned &Index,
662 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000663 unsigned &StructuredIndex,
664 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000665 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
666 // Explicitly braced initializer for complex type can be real+imaginary
667 // parts.
668 CheckComplexType(Entity, IList, DeclType, Index,
669 StructuredList, StructuredIndex);
670 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000671 CheckScalarType(Entity, IList, DeclType, Index,
672 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000673 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000675 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000676 } else if (DeclType->isAggregateType()) {
677 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000678 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000679 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000680 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000681 StructuredList, StructuredIndex,
682 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000683 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000684 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000685 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000686 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000688 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000689 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000690 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000691 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000692 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
693 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000694 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000695 if (!VerifyOnly)
696 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
697 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000698 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000699 } else if (DeclType->isRecordType()) {
700 // C++ [dcl.init]p14:
701 // [...] If the class is an aggregate (8.5.1), and the initializer
702 // is a brace-enclosed list, see 8.5.1.
703 //
704 // Note: 8.5.1 is handled below; here, we diagnose the case where
705 // we have an initializer list and a destination type that is not
706 // an aggregate.
707 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000708 if (!VerifyOnly)
709 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
710 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000711 hadError = true;
712 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000713 CheckReferenceType(Entity, IList, DeclType, Index,
714 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000715 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000716 if (!VerifyOnly)
717 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
718 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000719 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000720 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000721 if (!VerifyOnly)
722 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
723 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000724 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000725 }
726}
727
Anders Carlsson6cabf312010-01-23 23:23:01 +0000728void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000729 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000730 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000731 unsigned &Index,
732 InitListExpr *StructuredList,
733 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000734 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000735 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
736 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000737 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000738 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000739 = getStructuredSubobjectInit(IList, Index, ElemType,
740 StructuredList, StructuredIndex,
741 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000742 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 newStructuredList, newStructuredIndex);
744 ++StructuredIndex;
745 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000746 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000748 return CheckScalarType(Entity, IList, ElemType, Index,
749 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000750 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000751 return CheckReferenceType(Entity, IList, ElemType, Index,
752 StructuredList, StructuredIndex);
753 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000754
John McCall5decec92011-02-21 07:57:55 +0000755 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
756 // arrayType can be incomplete if we're initializing a flexible
757 // array member. There's nothing we can do with the completed
758 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759
John McCall5decec92011-02-21 07:57:55 +0000760 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000761 if (!VerifyOnly) {
762 CheckStringInit(Str, ElemType, arrayType, SemaRef);
763 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
764 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000765 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000766 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000767 }
John McCall5decec92011-02-21 07:57:55 +0000768
769 // Fall through for subaggregate initialization.
770
771 } else if (SemaRef.getLangOptions().CPlusPlus) {
772 // C++ [dcl.init.aggr]p12:
773 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000774 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000775 // an initializer-list. If the initializer can initialize a
776 // member, the member is initialized. [...]
777
778 // FIXME: Better EqualLoc?
779 InitializationKind Kind =
780 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
781 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
782
783 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000784 if (!VerifyOnly) {
785 ExprResult Result =
786 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
787 if (Result.isInvalid())
788 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000789
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000790 UpdateStructuredListElement(StructuredList, StructuredIndex,
791 Result.takeAs<Expr>());
792 }
John McCall5decec92011-02-21 07:57:55 +0000793 ++Index;
794 return;
795 }
796
797 // Fall through for subaggregate initialization
798 } else {
799 // C99 6.7.8p13:
800 //
801 // The initializer for a structure or union object that has
802 // automatic storage duration shall be either an initializer
803 // list as described below, or a single expression that has
804 // compatible structure or union type. In the latter case, the
805 // initial value of the object, including unnamed members, is
806 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000807 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000808 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000809 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
810 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000811 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000812 if (ExprRes.isInvalid())
813 hadError = true;
814 else {
815 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
816 if (ExprRes.isInvalid())
817 hadError = true;
818 }
819 UpdateStructuredListElement(StructuredList, StructuredIndex,
820 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000821 ++Index;
822 return;
823 }
John Wiegley01296292011-04-08 18:41:53 +0000824 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000825 // Fall through for subaggregate initialization
826 }
827
828 // C++ [dcl.init.aggr]p12:
829 //
830 // [...] Otherwise, if the member is itself a non-empty
831 // subaggregate, brace elision is assumed and the initializer is
832 // considered for the initialization of the first member of
833 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000834 if (!SemaRef.getLangOptions().OpenCL &&
835 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000836 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
837 StructuredIndex);
838 ++StructuredIndex;
839 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000840 if (!VerifyOnly) {
841 // We cannot initialize this element, so let
842 // PerformCopyInitialization produce the appropriate diagnostic.
843 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
844 SemaRef.Owned(expr),
845 /*TopLevelOfInitList=*/true);
846 }
John McCall5decec92011-02-21 07:57:55 +0000847 hadError = true;
848 ++Index;
849 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000850 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000851}
852
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000853void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
854 InitListExpr *IList, QualType DeclType,
855 unsigned &Index,
856 InitListExpr *StructuredList,
857 unsigned &StructuredIndex) {
858 assert(Index == 0 && "Index in explicit init list must be zero");
859
860 // As an extension, clang supports complex initializers, which initialize
861 // a complex number component-wise. When an explicit initializer list for
862 // a complex number contains two two initializers, this extension kicks in:
863 // it exepcts the initializer list to contain two elements convertible to
864 // the element type of the complex type. The first element initializes
865 // the real part, and the second element intitializes the imaginary part.
866
867 if (IList->getNumInits() != 2)
868 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
869 StructuredIndex);
870
871 // This is an extension in C. (The builtin _Complex type does not exist
872 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000873 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000874 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
875 << IList->getSourceRange();
876
877 // Initialize the complex number.
878 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
879 InitializedEntity ElementEntity =
880 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
881
882 for (unsigned i = 0; i < 2; ++i) {
883 ElementEntity.setElementIndex(Index);
884 CheckSubElementType(ElementEntity, IList, elementType, Index,
885 StructuredList, StructuredIndex);
886 }
887}
888
889
Anders Carlsson6cabf312010-01-23 23:23:01 +0000890void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000891 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000892 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000893 InitListExpr *StructuredList,
894 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000895 if (Index >= IList->getNumInits()) {
Sebastian Redl12757ab2011-09-24 17:48:14 +0000896 if (!SemaRef.getLangOptions().CPlusPlus0x) {
897 if (!VerifyOnly)
898 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
899 << IList->getSourceRange();
900 hadError = true;
901 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000902 ++Index;
903 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000904 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000905 }
John McCall643169b2010-11-11 00:46:36 +0000906
907 Expr *expr = IList->getInit(Index);
908 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000909 if (!VerifyOnly)
910 SemaRef.Diag(SubIList->getLocStart(),
911 diag::warn_many_braces_around_scalar_init)
912 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000913
914 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
915 StructuredIndex);
916 return;
917 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000918 if (!VerifyOnly)
919 SemaRef.Diag(expr->getSourceRange().getBegin(),
920 diag::err_designator_for_scalar_init)
921 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000922 hadError = true;
923 ++Index;
924 ++StructuredIndex;
925 return;
926 }
927
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000928 if (VerifyOnly) {
929 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
930 hadError = true;
931 ++Index;
932 return;
933 }
934
John McCall643169b2010-11-11 00:46:36 +0000935 ExprResult Result =
936 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000937 SemaRef.Owned(expr),
938 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000939
940 Expr *ResultExpr = 0;
941
942 if (Result.isInvalid())
943 hadError = true; // types weren't compatible.
944 else {
945 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946
John McCall643169b2010-11-11 00:46:36 +0000947 if (ResultExpr != expr) {
948 // The type was promoted, update initializer list.
949 IList->setInit(Index, ResultExpr);
950 }
951 }
952 if (hadError)
953 ++StructuredIndex;
954 else
955 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
956 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000957}
958
Anders Carlsson6cabf312010-01-23 23:23:01 +0000959void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
960 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000961 unsigned &Index,
962 InitListExpr *StructuredList,
963 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000964 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000965 // FIXME: It would be wonderful if we could point at the actual member. In
966 // general, it would be useful to pass location information down the stack,
967 // so that we know the location (or decl) of the "current object" being
968 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000969 if (!VerifyOnly)
970 SemaRef.Diag(IList->getLocStart(),
971 diag::err_init_reference_member_uninitialized)
972 << DeclType
973 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000974 hadError = true;
975 ++Index;
976 ++StructuredIndex;
977 return;
978 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000979
980 Expr *expr = IList->getInit(Index);
981 if (isa<InitListExpr>(expr)) {
982 // FIXME: Allowed in C++11.
983 if (!VerifyOnly)
984 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
985 << DeclType << IList->getSourceRange();
986 hadError = true;
987 ++Index;
988 ++StructuredIndex;
989 return;
990 }
991
992 if (VerifyOnly) {
993 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
994 hadError = true;
995 ++Index;
996 return;
997 }
998
999 ExprResult Result =
1000 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1001 SemaRef.Owned(expr),
1002 /*TopLevelOfInitList=*/true);
1003
1004 if (Result.isInvalid())
1005 hadError = true;
1006
1007 expr = Result.takeAs<Expr>();
1008 IList->setInit(Index, expr);
1009
1010 if (hadError)
1011 ++StructuredIndex;
1012 else
1013 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1014 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001015}
1016
Anders Carlsson6cabf312010-01-23 23:23:01 +00001017void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001018 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001019 unsigned &Index,
1020 InitListExpr *StructuredList,
1021 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001022 const VectorType *VT = DeclType->getAs<VectorType>();
1023 unsigned maxElements = VT->getNumElements();
1024 unsigned numEltsInit = 0;
1025 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001026
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001027 if (Index >= IList->getNumInits()) {
1028 // Make sure the element type can be value-initialized.
1029 if (VerifyOnly)
1030 CheckValueInitializable(
1031 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1032 return;
1033 }
1034
John McCall6a16b2f2010-10-30 00:11:39 +00001035 if (!SemaRef.getLangOptions().OpenCL) {
1036 // If the initializing element is a vector, try to copy-initialize
1037 // instead of breaking it apart (which is doomed to failure anyway).
1038 Expr *Init = IList->getInit(Index);
1039 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001040 if (VerifyOnly) {
1041 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1042 hadError = true;
1043 ++Index;
1044 return;
1045 }
1046
John McCall6a16b2f2010-10-30 00:11:39 +00001047 ExprResult Result =
1048 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001049 SemaRef.Owned(Init),
1050 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001051
1052 Expr *ResultExpr = 0;
1053 if (Result.isInvalid())
1054 hadError = true; // types weren't compatible.
1055 else {
1056 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001057
John McCall6a16b2f2010-10-30 00:11:39 +00001058 if (ResultExpr != Init) {
1059 // The type was promoted, update initializer list.
1060 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001061 }
1062 }
John McCall6a16b2f2010-10-30 00:11:39 +00001063 if (hadError)
1064 ++StructuredIndex;
1065 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001066 UpdateStructuredListElement(StructuredList, StructuredIndex,
1067 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001068 ++Index;
1069 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071
John McCall6a16b2f2010-10-30 00:11:39 +00001072 InitializedEntity ElementEntity =
1073 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001074
John McCall6a16b2f2010-10-30 00:11:39 +00001075 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1076 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001077 if (Index >= IList->getNumInits()) {
1078 if (VerifyOnly)
1079 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001080 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001082
John McCall6a16b2f2010-10-30 00:11:39 +00001083 ElementEntity.setElementIndex(Index);
1084 CheckSubElementType(ElementEntity, IList, elementType, Index,
1085 StructuredList, StructuredIndex);
1086 }
1087 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001088 }
John McCall6a16b2f2010-10-30 00:11:39 +00001089
1090 InitializedEntity ElementEntity =
1091 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001092
John McCall6a16b2f2010-10-30 00:11:39 +00001093 // OpenCL initializers allows vectors to be constructed from vectors.
1094 for (unsigned i = 0; i < maxElements; ++i) {
1095 // Don't attempt to go past the end of the init list
1096 if (Index >= IList->getNumInits())
1097 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
John McCall6a16b2f2010-10-30 00:11:39 +00001099 ElementEntity.setElementIndex(Index);
1100
1101 QualType IType = IList->getInit(Index)->getType();
1102 if (!IType->isVectorType()) {
1103 CheckSubElementType(ElementEntity, IList, elementType, Index,
1104 StructuredList, StructuredIndex);
1105 ++numEltsInit;
1106 } else {
1107 QualType VecType;
1108 const VectorType *IVT = IType->getAs<VectorType>();
1109 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
John McCall6a16b2f2010-10-30 00:11:39 +00001111 if (IType->isExtVectorType())
1112 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1113 else
1114 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001115 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001116 CheckSubElementType(ElementEntity, IList, VecType, Index,
1117 StructuredList, StructuredIndex);
1118 numEltsInit += numIElts;
1119 }
1120 }
1121
1122 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001123 if (numEltsInit != maxElements) {
1124 if (!VerifyOnly)
1125 SemaRef.Diag(IList->getSourceRange().getBegin(),
1126 diag::err_vector_incorrect_num_initializers)
1127 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1128 hadError = true;
1129 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001130}
1131
Anders Carlsson6cabf312010-01-23 23:23:01 +00001132void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001133 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001134 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001135 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001136 unsigned &Index,
1137 InitListExpr *StructuredList,
1138 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001139 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1140
Steve Narofff8ecff22008-05-01 22:18:59 +00001141 // Check for the special-case of initializing an array with a string.
1142 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001143 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001144 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001145 // We place the string literal directly into the resulting
1146 // initializer list. This is the only place where the structure
1147 // of the structured initializer list doesn't match exactly,
1148 // because doing so would involve allocating one character
1149 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001150 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001151 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001152 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1153 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1154 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001155 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001156 return;
1157 }
1158 }
John McCall66884dd2011-02-21 07:22:22 +00001159 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001160 // Check for VLAs; in standard C it would be possible to check this
1161 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1162 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001163 if (!VerifyOnly)
1164 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1165 diag::err_variable_object_no_init)
1166 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001167 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001168 ++Index;
1169 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001170 return;
1171 }
1172
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001173 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001174 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1175 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001176 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001177 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001178 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001179 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001180 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001181 maxElementsKnown = true;
1182 }
1183
John McCall66884dd2011-02-21 07:22:22 +00001184 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 while (Index < IList->getNumInits()) {
1186 Expr *Init = IList->getInit(Index);
1187 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001188 // If we're not the subobject that matches up with the '{' for
1189 // the designator, we shouldn't be handling the
1190 // designator. Return immediately.
1191 if (!SubobjectIsDesignatorContext)
1192 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001194 // Handle this designated initializer. elementIndex will be
1195 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001196 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001197 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001198 StructuredList, StructuredIndex, true,
1199 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001200 hadError = true;
1201 continue;
1202 }
1203
Douglas Gregor033d1252009-01-23 16:54:12 +00001204 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001205 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001206 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001207 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001208 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001209
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001210 // If the array is of incomplete type, keep track of the number of
1211 // elements in the initializer.
1212 if (!maxElementsKnown && elementIndex > maxElements)
1213 maxElements = elementIndex;
1214
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001215 continue;
1216 }
1217
1218 // If we know the maximum number of elements, and we've already
1219 // hit it, stop consuming elements in the initializer list.
1220 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001221 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001222
Anders Carlsson6cabf312010-01-23 23:23:01 +00001223 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001224 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001225 Entity);
1226 // Check this element.
1227 CheckSubElementType(ElementEntity, IList, elementType, Index,
1228 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001229 ++elementIndex;
1230
1231 // If the array is of incomplete type, keep track of the number of
1232 // elements in the initializer.
1233 if (!maxElementsKnown && elementIndex > maxElements)
1234 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001235 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001236 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001237 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001238 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001239 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001240 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001241 // Sizing an array implicitly to zero is not allowed by ISO C,
1242 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001243 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001244 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001245 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001246
Mike Stump11289f42009-09-09 15:08:12 +00001247 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001248 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001250 if (!hadError && VerifyOnly) {
1251 // Check if there are any members of the array that get value-initialized.
1252 // If so, check if doing that is possible.
1253 // FIXME: This needs to detect holes left by designated initializers too.
1254 if (maxElementsKnown && elementIndex < maxElements)
1255 CheckValueInitializable(InitializedEntity::InitializeElement(
1256 SemaRef.Context, 0, Entity));
1257 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001258}
1259
Eli Friedman3fa64df2011-08-23 22:24:57 +00001260bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1261 Expr *InitExpr,
1262 FieldDecl *Field,
1263 bool TopLevelObject) {
1264 // Handle GNU flexible array initializers.
1265 unsigned FlexArrayDiag;
1266 if (isa<InitListExpr>(InitExpr) &&
1267 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1268 // Empty flexible array init always allowed as an extension
1269 FlexArrayDiag = diag::ext_flexible_array_init;
1270 } else if (SemaRef.getLangOptions().CPlusPlus) {
1271 // Disallow flexible array init in C++; it is not required for gcc
1272 // compatibility, and it needs work to IRGen correctly in general.
1273 FlexArrayDiag = diag::err_flexible_array_init;
1274 } else if (!TopLevelObject) {
1275 // Disallow flexible array init on non-top-level object
1276 FlexArrayDiag = diag::err_flexible_array_init;
1277 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1278 // Disallow flexible array init on anything which is not a variable.
1279 FlexArrayDiag = diag::err_flexible_array_init;
1280 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1281 // Disallow flexible array init on local variables.
1282 FlexArrayDiag = diag::err_flexible_array_init;
1283 } else {
1284 // Allow other cases.
1285 FlexArrayDiag = diag::ext_flexible_array_init;
1286 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001287
1288 if (!VerifyOnly) {
1289 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1290 FlexArrayDiag)
1291 << InitExpr->getSourceRange().getBegin();
1292 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1293 << Field;
1294 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001295
1296 return FlexArrayDiag != diag::ext_flexible_array_init;
1297}
1298
Anders Carlsson6cabf312010-01-23 23:23:01 +00001299void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001300 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001301 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001302 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001303 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001304 unsigned &Index,
1305 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001306 unsigned &StructuredIndex,
1307 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001308 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001309
Eli Friedman23a9e312008-05-19 19:16:24 +00001310 // If the record is invalid, some of it's members are invalid. To avoid
1311 // confusion, we forgo checking the intializer for the entire record.
1312 if (structDecl->isInvalidDecl()) {
1313 hadError = true;
1314 return;
Mike Stump11289f42009-09-09 15:08:12 +00001315 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001316
1317 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001318 // Value-initialize the first named member of the union.
1319 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1320 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1321 Field != FieldEnd; ++Field) {
1322 if (Field->getDeclName()) {
1323 if (VerifyOnly)
1324 CheckValueInitializable(
1325 InitializedEntity::InitializeMember(*Field, &Entity));
1326 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001327 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001328 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001329 }
1330 }
1331 return;
1332 }
1333
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001334 // If structDecl is a forward declaration, this loop won't do
1335 // anything except look at designated initializers; That's okay,
1336 // because an error should get printed out elsewhere. It might be
1337 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001338 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001339 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001340 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001341 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001342 while (Index < IList->getNumInits()) {
1343 Expr *Init = IList->getInit(Index);
1344
1345 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001346 // If we're not the subobject that matches up with the '{' for
1347 // the designator, we shouldn't be handling the
1348 // designator. Return immediately.
1349 if (!SubobjectIsDesignatorContext)
1350 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001351
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001352 // Handle this designated initializer. Field will be updated to
1353 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001354 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001355 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001356 StructuredList, StructuredIndex,
1357 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 hadError = true;
1359
Douglas Gregora9add4e2009-02-12 19:00:39 +00001360 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001361
1362 // Disable check for missing fields when designators are used.
1363 // This matches gcc behaviour.
1364 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001365 continue;
1366 }
1367
1368 if (Field == FieldEnd) {
1369 // We've run out of fields. We're done.
1370 break;
1371 }
1372
Douglas Gregora9add4e2009-02-12 19:00:39 +00001373 // We've already initialized a member of a union. We're done.
1374 if (InitializedSomething && DeclType->isUnionType())
1375 break;
1376
Douglas Gregor91f84212008-12-11 16:49:14 +00001377 // If we've hit the flexible array member at the end, we're done.
1378 if (Field->getType()->isIncompleteArrayType())
1379 break;
1380
Douglas Gregor51695702009-01-29 16:53:55 +00001381 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001382 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001383 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001384 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001385 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001386
Douglas Gregora82064c2011-06-29 21:51:31 +00001387 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001388 bool InvalidUse;
1389 if (VerifyOnly)
1390 InvalidUse = !SemaRef.CanUseDecl(*Field);
1391 else
1392 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1393 IList->getInit(Index)->getLocStart());
1394 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001395 ++Index;
1396 ++Field;
1397 hadError = true;
1398 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001399 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001400
Anders Carlsson6cabf312010-01-23 23:23:01 +00001401 InitializedEntity MemberEntity =
1402 InitializedEntity::InitializeMember(*Field, &Entity);
1403 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1404 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001405 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001406
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001407 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001408 // Initialize the first field within the union.
1409 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001410 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001411
1412 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001413 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001414
John McCalle40b58e2010-03-11 19:32:38 +00001415 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001416 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1417 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1418 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001419 // It is possible we have one or more unnamed bitfields remaining.
1420 // Find first (if any) named field and emit warning.
1421 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1422 it != end; ++it) {
1423 if (!it->isUnnamedBitfield()) {
1424 SemaRef.Diag(IList->getSourceRange().getEnd(),
1425 diag::warn_missing_field_initializers) << it->getName();
1426 break;
1427 }
1428 }
1429 }
1430
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001431 // Check that any remaining fields can be value-initialized.
1432 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1433 !Field->getType()->isIncompleteArrayType()) {
1434 // FIXME: Should check for holes left by designated initializers too.
1435 for (; Field != FieldEnd && !hadError; ++Field) {
1436 if (!Field->isUnnamedBitfield())
1437 CheckValueInitializable(
1438 InitializedEntity::InitializeMember(*Field, &Entity));
1439 }
1440 }
1441
Mike Stump11289f42009-09-09 15:08:12 +00001442 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001443 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001444 return;
1445
Eli Friedman3fa64df2011-08-23 22:24:57 +00001446 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1447 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001448 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001449 ++Index;
1450 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001451 }
1452
Anders Carlsson6cabf312010-01-23 23:23:01 +00001453 InitializedEntity MemberEntity =
1454 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455
Anders Carlsson6cabf312010-01-23 23:23:01 +00001456 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001457 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001458 StructuredList, StructuredIndex);
1459 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001460 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001461 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001462}
Steve Narofff8ecff22008-05-01 22:18:59 +00001463
Douglas Gregord5846a12009-04-15 06:41:24 +00001464/// \brief Expand a field designator that refers to a member of an
1465/// anonymous struct or union into a series of field designators that
1466/// refers to the field within the appropriate subobject.
1467///
Douglas Gregord5846a12009-04-15 06:41:24 +00001468static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001469 DesignatedInitExpr *DIE,
1470 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001471 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001472 typedef DesignatedInitExpr::Designator Designator;
1473
Douglas Gregord5846a12009-04-15 06:41:24 +00001474 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001475 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001476 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1477 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1478 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001479 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001480 DIE->getDesignator(DesigIdx)->getDotLoc(),
1481 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1482 else
1483 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1484 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001485 assert(isa<FieldDecl>(*PI));
1486 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001487 }
1488
1489 // Expand the current designator into the set of replacement
1490 // designators, so we have a full subobject path down to where the
1491 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001492 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001493 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001494}
Mike Stump11289f42009-09-09 15:08:12 +00001495
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001497/// corresponds to FieldName.
1498static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1499 IdentifierInfo *FieldName) {
1500 assert(AnonField->isAnonymousStructOrUnion());
1501 Decl *NextDecl = AnonField->getNextDeclInContext();
1502 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1503 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1504 return IF;
1505 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001506 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001507 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001508}
1509
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001510static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1511 DesignatedInitExpr *DIE) {
1512 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1513 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1514 for (unsigned I = 0; I < NumIndexExprs; ++I)
1515 IndexExprs[I] = DIE->getSubExpr(I + 1);
1516 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1517 DIE->size(), IndexExprs.data(),
1518 NumIndexExprs, DIE->getEqualOrColonLoc(),
1519 DIE->usesGNUSyntax(), DIE->getInit());
1520}
1521
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001522/// @brief Check the well-formedness of a C99 designated initializer.
1523///
1524/// Determines whether the designated initializer @p DIE, which
1525/// resides at the given @p Index within the initializer list @p
1526/// IList, is well-formed for a current object of type @p DeclType
1527/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001528/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001529/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001530///
1531/// @param IList The initializer list in which this designated
1532/// initializer occurs.
1533///
Douglas Gregora5324162009-04-15 04:56:10 +00001534/// @param DIE The designated initializer expression.
1535///
1536/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001537///
1538/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1539/// into which the designation in @p DIE should refer.
1540///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001541/// @param NextField If non-NULL and the first designator in @p DIE is
1542/// a field, this will be set to the field declaration corresponding
1543/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001544///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001545/// @param NextElementIndex If non-NULL and the first designator in @p
1546/// DIE is an array designator or GNU array-range designator, this
1547/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001548///
1549/// @param Index Index into @p IList where the designated initializer
1550/// @p DIE occurs.
1551///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001552/// @param StructuredList The initializer list expression that
1553/// describes all of the subobject initializers in the order they'll
1554/// actually be initialized.
1555///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001556/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001557bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001558InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001559 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001560 DesignatedInitExpr *DIE,
1561 unsigned DesigIdx,
1562 QualType &CurrentObjectType,
1563 RecordDecl::field_iterator *NextField,
1564 llvm::APSInt *NextElementIndex,
1565 unsigned &Index,
1566 InitListExpr *StructuredList,
1567 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001568 bool FinishSubobjectInit,
1569 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001570 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571 // Check the actual initialization for the designated object type.
1572 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001573
1574 // Temporarily remove the designator expression from the
1575 // initializer list that the child calls see, so that we don't try
1576 // to re-process the designator.
1577 unsigned OldIndex = Index;
1578 IList->setInit(OldIndex, DIE->getInit());
1579
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001580 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001581 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001582
1583 // Restore the designated initializer expression in the syntactic
1584 // form of the initializer list.
1585 if (IList->getInit(OldIndex) != DIE->getInit())
1586 DIE->setInit(IList->getInit(OldIndex));
1587 IList->setInit(OldIndex, DIE);
1588
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001590 }
1591
Douglas Gregora5324162009-04-15 04:56:10 +00001592 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001593 bool IsFirstDesignator = (DesigIdx == 0);
1594 if (!VerifyOnly) {
1595 assert((IsFirstDesignator || StructuredList) &&
1596 "Need a non-designated initializer list to start from");
1597
1598 // Determine the structural initializer list that corresponds to the
1599 // current subobject.
1600 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1601 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1602 StructuredList, StructuredIndex,
1603 SourceRange(D->getStartLocation(),
1604 DIE->getSourceRange().getEnd()));
1605 assert(StructuredList && "Expected a structured initializer list");
1606 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001607
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001608 if (D->isFieldDesignator()) {
1609 // C99 6.7.8p7:
1610 //
1611 // If a designator has the form
1612 //
1613 // . identifier
1614 //
1615 // then the current object (defined below) shall have
1616 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001617 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001618 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619 if (!RT) {
1620 SourceLocation Loc = D->getDotLoc();
1621 if (Loc.isInvalid())
1622 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001623 if (!VerifyOnly)
1624 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1625 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001626 ++Index;
1627 return true;
1628 }
1629
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001630 // Note: we perform a linear search of the fields here, despite
1631 // the fact that we have a faster lookup method, because we always
1632 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001633 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001634 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001635 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001636 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001637 Field = RT->getDecl()->field_begin(),
1638 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639 for (; Field != FieldEnd; ++Field) {
1640 if (Field->isUnnamedBitfield())
1641 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001643 // If we find a field representing an anonymous field, look in the
1644 // IndirectFieldDecl that follow for the designated initializer.
1645 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1646 if (IndirectFieldDecl *IF =
1647 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001648 // In verify mode, don't modify the original.
1649 if (VerifyOnly)
1650 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001651 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1652 D = DIE->getDesignator(DesigIdx);
1653 break;
1654 }
1655 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001656 if (KnownField && KnownField == *Field)
1657 break;
1658 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001659 break;
1660
1661 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662 }
1663
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001664 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001665 if (VerifyOnly) {
1666 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001667 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001668 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001669
Douglas Gregord5846a12009-04-15 06:41:24 +00001670 // There was no normal field in the struct with the designated
1671 // name. Perform another lookup for this name, which may find
1672 // something that we can't designate (e.g., a member function),
1673 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001674 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001675 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001676 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001677 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001678 // Name lookup didn't find anything. Determine whether this
1679 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001681 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001682 TypoCorrection Corrected = SemaRef.CorrectTypo(
1683 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1684 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1685 RT->getDecl(), false, Sema::CTC_NoKeywords);
1686 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001687 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001688 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001689 std::string CorrectedStr(
1690 Corrected.getAsString(SemaRef.getLangOptions()));
1691 std::string CorrectedQuotedStr(
1692 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001693 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001694 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001695 << FieldName << CurrentObjectType << CorrectedQuotedStr
1696 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001698 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001699 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001700 } else {
1701 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1702 << FieldName << CurrentObjectType;
1703 ++Index;
1704 return true;
1705 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001707
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001710 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001712 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001713 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001714 ++Index;
1715 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001716 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001717
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001718 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001719 // The replacement field comes from typo correction; find it
1720 // in the list of fields.
1721 FieldIndex = 0;
1722 Field = RT->getDecl()->field_begin();
1723 for (; Field != FieldEnd; ++Field) {
1724 if (Field->isUnnamedBitfield())
1725 continue;
1726
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001728 Field->getIdentifier() == ReplacementField->getIdentifier())
1729 break;
1730
1731 ++FieldIndex;
1732 }
1733 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001734 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001735
1736 // All of the fields of a union are located at the same place in
1737 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001738 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001740 if (!VerifyOnly)
1741 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001742 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743
Douglas Gregora82064c2011-06-29 21:51:31 +00001744 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001745 bool InvalidUse;
1746 if (VerifyOnly)
1747 InvalidUse = !SemaRef.CanUseDecl(*Field);
1748 else
1749 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1750 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001751 ++Index;
1752 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001753 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001754
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001755 if (!VerifyOnly) {
1756 // Update the designator with the field declaration.
1757 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001758
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001759 // Make sure that our non-designated initializer list has space
1760 // for a subobject corresponding to this field.
1761 if (FieldIndex >= StructuredList->getNumInits())
1762 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1763 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001764
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001765 // This designator names a flexible array member.
1766 if (Field->getType()->isIncompleteArrayType()) {
1767 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001768 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001769 // We can't designate an object within the flexible array
1770 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001771 if (!VerifyOnly) {
1772 DesignatedInitExpr::Designator *NextD
1773 = DIE->getDesignator(DesigIdx + 1);
1774 SemaRef.Diag(NextD->getStartLocation(),
1775 diag::err_designator_into_flexible_array_member)
1776 << SourceRange(NextD->getStartLocation(),
1777 DIE->getSourceRange().getEnd());
1778 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1779 << *Field;
1780 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001781 Invalid = true;
1782 }
1783
Chris Lattner001b29c2010-10-10 17:49:49 +00001784 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1785 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001786 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001787 if (!VerifyOnly) {
1788 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1789 diag::err_flexible_array_init_needs_braces)
1790 << DIE->getInit()->getSourceRange();
1791 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1792 << *Field;
1793 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001794 Invalid = true;
1795 }
1796
Eli Friedman3fa64df2011-08-23 22:24:57 +00001797 // Check GNU flexible array initializer.
1798 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1799 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001800 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001801
1802 if (Invalid) {
1803 ++Index;
1804 return true;
1805 }
1806
1807 // Initialize the array.
1808 bool prevHadError = hadError;
1809 unsigned newStructuredIndex = FieldIndex;
1810 unsigned OldIndex = Index;
1811 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001812
1813 InitializedEntity MemberEntity =
1814 InitializedEntity::InitializeMember(*Field, &Entity);
1815 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001816 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001817
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001818 IList->setInit(OldIndex, DIE);
1819 if (hadError && !prevHadError) {
1820 ++Field;
1821 ++FieldIndex;
1822 if (NextField)
1823 *NextField = Field;
1824 StructuredIndex = FieldIndex;
1825 return true;
1826 }
1827 } else {
1828 // Recurse to check later designated subobjects.
1829 QualType FieldType = (*Field)->getType();
1830 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001832 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001833 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001834 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1835 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001836 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001837 true, false))
1838 return true;
1839 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001840
1841 // Find the position of the next field to be initialized in this
1842 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001843 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001844 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001845
1846 // If this the first designator, our caller will continue checking
1847 // the rest of this struct/class/union subobject.
1848 if (IsFirstDesignator) {
1849 if (NextField)
1850 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001851 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001852 return false;
1853 }
1854
Douglas Gregor17bd0942009-01-28 23:36:17 +00001855 if (!FinishSubobjectInit)
1856 return false;
1857
Douglas Gregord5846a12009-04-15 06:41:24 +00001858 // We've already initialized something in the union; we're done.
1859 if (RT->getDecl()->isUnion())
1860 return hadError;
1861
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001862 // Check the remaining fields within this class/struct/union subobject.
1863 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
Anders Carlsson6cabf312010-01-23 23:23:01 +00001865 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001866 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001867 return hadError && !prevHadError;
1868 }
1869
1870 // C99 6.7.8p6:
1871 //
1872 // If a designator has the form
1873 //
1874 // [ constant-expression ]
1875 //
1876 // then the current object (defined below) shall have array
1877 // type and the expression shall be an integer constant
1878 // expression. If the array is of unknown size, any
1879 // nonnegative value is valid.
1880 //
1881 // Additionally, cope with the GNU extension that permits
1882 // designators of the form
1883 //
1884 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001885 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001886 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001887 if (!VerifyOnly)
1888 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1889 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001890 ++Index;
1891 return true;
1892 }
1893
1894 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001895 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1896 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001897 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001898 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001899 DesignatedEndIndex = DesignatedStartIndex;
1900 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001901 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001902
Mike Stump11289f42009-09-09 15:08:12 +00001903 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001904 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001905 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001906 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001907 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001908
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001909 // Codegen can't handle evaluating array range designators that have side
1910 // effects, because we replicate the AST value for each initialized element.
1911 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1912 // elements with something that has a side effect, so codegen can emit an
1913 // "error unsupported" error instead of miscompiling the app.
1914 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001915 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001916 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001917 }
1918
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001919 if (isa<ConstantArrayType>(AT)) {
1920 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001921 DesignatedStartIndex
1922 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001923 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001924 DesignatedEndIndex
1925 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001926 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1927 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001928 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001929 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1930 diag::err_array_designator_too_large)
1931 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1932 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001933 ++Index;
1934 return true;
1935 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001936 } else {
1937 // Make sure the bit-widths and signedness match.
1938 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001939 DesignatedEndIndex
1940 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001941 else if (DesignatedStartIndex.getBitWidth() <
1942 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001943 DesignatedStartIndex
1944 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001945 DesignatedStartIndex.setIsUnsigned(true);
1946 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 }
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001949 // Make sure that our non-designated initializer list has space
1950 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001951 if (!VerifyOnly &&
1952 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001953 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001954 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001955
Douglas Gregor17bd0942009-01-28 23:36:17 +00001956 // Repeatedly perform subobject initializations in the range
1957 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001958
Douglas Gregor17bd0942009-01-28 23:36:17 +00001959 // Move to the next designator
1960 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1961 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001963 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001964 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001965
Douglas Gregor17bd0942009-01-28 23:36:17 +00001966 while (DesignatedStartIndex <= DesignatedEndIndex) {
1967 // Recurse to check later designated subobjects.
1968 QualType ElementType = AT->getElementType();
1969 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001971 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1973 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001974 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001975 (DesignatedStartIndex == DesignatedEndIndex),
1976 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001977 return true;
1978
1979 // Move to the next index in the array that we'll be initializing.
1980 ++DesignatedStartIndex;
1981 ElementIndex = DesignatedStartIndex.getZExtValue();
1982 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001983
1984 // If this the first designator, our caller will continue checking
1985 // the rest of this array subobject.
1986 if (IsFirstDesignator) {
1987 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001988 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001989 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001990 return false;
1991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor17bd0942009-01-28 23:36:17 +00001993 if (!FinishSubobjectInit)
1994 return false;
1995
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001996 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001997 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001999 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002000 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002001 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002002}
2003
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002004// Get the structured initializer list for a subobject of type
2005// @p CurrentObjectType.
2006InitListExpr *
2007InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2008 QualType CurrentObjectType,
2009 InitListExpr *StructuredList,
2010 unsigned StructuredIndex,
2011 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002012 if (VerifyOnly)
2013 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002014 Expr *ExistingInit = 0;
2015 if (!StructuredList)
2016 ExistingInit = SyntacticToSemantic[IList];
2017 else if (StructuredIndex < StructuredList->getNumInits())
2018 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002019
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002020 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2021 return Result;
2022
2023 if (ExistingInit) {
2024 // We are creating an initializer list that initializes the
2025 // subobjects of the current object, but there was already an
2026 // initialization that completely initialized the current
2027 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002028 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002029 // struct X { int a, b; };
2030 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002031 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002032 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2033 // designated initializer re-initializes the whole
2034 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002035 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002036 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002037 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002038 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002039 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002040 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002041 << ExistingInit->getSourceRange();
2042 }
2043
Mike Stump11289f42009-09-09 15:08:12 +00002044 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002045 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2046 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002047 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002048
Douglas Gregora8a089b2010-07-13 18:40:04 +00002049 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050
Douglas Gregor6d00c992009-03-20 23:58:33 +00002051 // Pre-allocate storage for the structured initializer list.
2052 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002053 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002054 bool GotNumInits = false;
2055 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002056 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002057 GotNumInits = true;
2058 } else if (Index < IList->getNumInits()) {
2059 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002060 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002061 GotNumInits = true;
2062 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002063 }
2064
Mike Stump11289f42009-09-09 15:08:12 +00002065 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002066 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2067 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2068 NumElements = CAType->getSize().getZExtValue();
2069 // Simple heuristic so that we don't allocate a very large
2070 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002071 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002072 NumElements = 0;
2073 }
John McCall9dd450b2009-09-21 23:43:11 +00002074 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002075 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002077 RecordDecl *RDecl = RType->getDecl();
2078 if (RDecl->isUnion())
2079 NumElements = 1;
2080 else
Mike Stump11289f42009-09-09 15:08:12 +00002081 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002082 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002083 }
2084
Ted Kremenekac034612010-04-13 23:39:13 +00002085 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002086
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002087 // Link this new initializer list into the structured initializer
2088 // lists.
2089 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002090 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002091 else {
2092 Result->setSyntacticForm(IList);
2093 SyntacticToSemantic[IList] = Result;
2094 }
2095
2096 return Result;
2097}
2098
2099/// Update the initializer at index @p StructuredIndex within the
2100/// structured initializer list to the value @p expr.
2101void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2102 unsigned &StructuredIndex,
2103 Expr *expr) {
2104 // No structured initializer list to update
2105 if (!StructuredList)
2106 return;
2107
Ted Kremenekac034612010-04-13 23:39:13 +00002108 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2109 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002110 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002111 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002112 diag::warn_initializer_overrides)
2113 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002114 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002115 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002116 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002117 << PrevInit->getSourceRange();
2118 }
Mike Stump11289f42009-09-09 15:08:12 +00002119
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002120 ++StructuredIndex;
2121}
2122
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002123/// Check that the given Index expression is a valid array designator
2124/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002125/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002126/// and produces a reasonable diagnostic if there is a
2127/// failure. Returns true if there was an error, false otherwise. If
2128/// everything went okay, Value will receive the value of the constant
2129/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002130static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002131CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002132 SourceLocation Loc = Index->getSourceRange().getBegin();
2133
2134 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002135 if (S.VerifyIntegerConstantExpression(Index, &Value))
2136 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002137
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002138 if (Value.isSigned() && Value.isNegative())
2139 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002140 << Value.toString(10) << Index->getSourceRange();
2141
Douglas Gregor51650d32009-01-23 21:04:18 +00002142 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002143 return false;
2144}
2145
John McCalldadc5752010-08-24 06:29:42 +00002146ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002147 SourceLocation Loc,
2148 bool GNUSyntax,
2149 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002150 typedef DesignatedInitExpr::Designator ASTDesignator;
2151
2152 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002153 SmallVector<ASTDesignator, 32> Designators;
2154 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002155
2156 // Build designators and check array designator expressions.
2157 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2158 const Designator &D = Desig.getDesignator(Idx);
2159 switch (D.getKind()) {
2160 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002161 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002162 D.getFieldLoc()));
2163 break;
2164
2165 case Designator::ArrayDesignator: {
2166 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2167 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002168 if (!Index->isTypeDependent() &&
2169 !Index->isValueDependent() &&
2170 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 Invalid = true;
2172 else {
2173 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002174 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002175 D.getRBracketLoc()));
2176 InitExpressions.push_back(Index);
2177 }
2178 break;
2179 }
2180
2181 case Designator::ArrayRangeDesignator: {
2182 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2183 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2184 llvm::APSInt StartValue;
2185 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002186 bool StartDependent = StartIndex->isTypeDependent() ||
2187 StartIndex->isValueDependent();
2188 bool EndDependent = EndIndex->isTypeDependent() ||
2189 EndIndex->isValueDependent();
2190 if ((!StartDependent &&
2191 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2192 (!EndDependent &&
2193 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002194 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002195 else {
2196 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002197 if (StartDependent || EndDependent) {
2198 // Nothing to compute.
2199 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002200 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002201 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002202 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002203
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002204 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002205 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002206 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002207 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2208 Invalid = true;
2209 } else {
2210 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002211 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002212 D.getEllipsisLoc(),
2213 D.getRBracketLoc()));
2214 InitExpressions.push_back(StartIndex);
2215 InitExpressions.push_back(EndIndex);
2216 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002217 }
2218 break;
2219 }
2220 }
2221 }
2222
2223 if (Invalid || Init.isInvalid())
2224 return ExprError();
2225
2226 // Clear out the expressions within the designation.
2227 Desig.ClearExprs(*this);
2228
2229 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002230 = DesignatedInitExpr::Create(Context,
2231 Designators.data(), Designators.size(),
2232 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002233 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002234
Douglas Gregorc124e592011-01-16 16:13:16 +00002235 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002236 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2237 << DIE->getSourceRange();
2238 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002239 Diag(DIE->getLocStart(), diag::ext_designated_init)
2240 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002241
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002242 return Owned(DIE);
2243}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002244
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002245//===----------------------------------------------------------------------===//
2246// Initialization entity
2247//===----------------------------------------------------------------------===//
2248
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002249InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002250 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002252{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002253 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2254 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002255 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002256 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002257 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002258 Type = VT->getElementType();
2259 } else {
2260 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2261 assert(CT && "Unexpected type");
2262 Kind = EK_ComplexElement;
2263 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002264 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002265}
2266
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002267InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002268 CXXBaseSpecifier *Base,
2269 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002270{
2271 InitializedEntity Result;
2272 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002273 Result.Base = reinterpret_cast<uintptr_t>(Base);
2274 if (IsInheritedVirtualBase)
2275 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002276
Douglas Gregor1b303932009-12-22 15:35:07 +00002277 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002278 return Result;
2279}
2280
Douglas Gregor85dabae2009-12-16 01:38:02 +00002281DeclarationName InitializedEntity::getName() const {
2282 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002283 case EK_Parameter: {
2284 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2285 return (D ? D->getDeclName() : DeclarationName());
2286 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002287
2288 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002289 case EK_Member:
2290 return VariableOrMember->getDeclName();
2291
2292 case EK_Result:
2293 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002294 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002295 case EK_Temporary:
2296 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002297 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002298 case EK_ArrayElement:
2299 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002300 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002301 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002302 return DeclarationName();
2303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304
Douglas Gregor85dabae2009-12-16 01:38:02 +00002305 // Silence GCC warning
2306 return DeclarationName();
2307}
2308
Douglas Gregora4b592a2009-12-19 03:01:41 +00002309DeclaratorDecl *InitializedEntity::getDecl() const {
2310 switch (getKind()) {
2311 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002312 case EK_Member:
2313 return VariableOrMember;
2314
John McCall31168b02011-06-15 23:02:42 +00002315 case EK_Parameter:
2316 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2317
Douglas Gregora4b592a2009-12-19 03:01:41 +00002318 case EK_Result:
2319 case EK_Exception:
2320 case EK_New:
2321 case EK_Temporary:
2322 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002323 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002324 case EK_ArrayElement:
2325 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002326 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002327 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002328 return 0;
2329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002330
Douglas Gregora4b592a2009-12-19 03:01:41 +00002331 // Silence GCC warning
2332 return 0;
2333}
2334
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002335bool InitializedEntity::allowsNRVO() const {
2336 switch (getKind()) {
2337 case EK_Result:
2338 case EK_Exception:
2339 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002340
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002341 case EK_Variable:
2342 case EK_Parameter:
2343 case EK_Member:
2344 case EK_New:
2345 case EK_Temporary:
2346 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002347 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002348 case EK_ArrayElement:
2349 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002350 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002351 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002352 break;
2353 }
2354
2355 return false;
2356}
2357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002358//===----------------------------------------------------------------------===//
2359// Initialization sequence
2360//===----------------------------------------------------------------------===//
2361
2362void InitializationSequence::Step::Destroy() {
2363 switch (Kind) {
2364 case SK_ResolveAddressOfOverloadedFunction:
2365 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002366 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002367 case SK_CastDerivedToBaseLValue:
2368 case SK_BindReference:
2369 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002370 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002371 case SK_UserConversion:
2372 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002373 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002374 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002375 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002376 case SK_ListConstructorCall:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002377 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002378 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002379 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002380 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002381 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002382 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002383 case SK_PassByIndirectCopyRestore:
2384 case SK_PassByIndirectRestore:
2385 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002386 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002388 case SK_ConversionSequence:
2389 delete ICS;
2390 }
2391}
2392
Douglas Gregor838fcc32010-03-26 20:14:36 +00002393bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002394 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002395}
2396
2397bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002398 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002400
Douglas Gregor838fcc32010-03-26 20:14:36 +00002401 switch (getFailureKind()) {
2402 case FK_TooManyInitsForReference:
2403 case FK_ArrayNeedsInitList:
2404 case FK_ArrayNeedsInitListOrStringLiteral:
2405 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2406 case FK_NonConstLValueReferenceBindingToTemporary:
2407 case FK_NonConstLValueReferenceBindingToUnrelated:
2408 case FK_RValueReferenceBindingToLValue:
2409 case FK_ReferenceInitDropsQualifiers:
2410 case FK_ReferenceInitFailed:
2411 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002412 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002413 case FK_TooManyInitsForScalar:
2414 case FK_ReferenceBindingToInitList:
2415 case FK_InitListBadDestinationType:
2416 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002417 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002418 case FK_ArrayTypeMismatch:
2419 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002420 case FK_ListInitializationFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002421 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002422
Douglas Gregor838fcc32010-03-26 20:14:36 +00002423 case FK_ReferenceInitOverloadFailed:
2424 case FK_UserConversionOverloadFailed:
2425 case FK_ConstructorOverloadFailed:
2426 return FailedOverloadResult == OR_Ambiguous;
2427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428
Douglas Gregor838fcc32010-03-26 20:14:36 +00002429 return false;
2430}
2431
Douglas Gregorb33eed02010-04-16 22:09:46 +00002432bool InitializationSequence::isConstructorInitialization() const {
2433 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2434}
2435
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002436bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2437 const Expr *Initializer,
2438 bool *isInitializerConstant,
2439 APValue *ConstantValue) const {
2440 if (Steps.empty() || Initializer->isValueDependent())
2441 return false;
2442
2443 const Step &LastStep = Steps.back();
2444 if (LastStep.Kind != SK_ConversionSequence)
2445 return false;
2446
2447 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2448 const StandardConversionSequence *SCS = NULL;
2449 switch (ICS.getKind()) {
2450 case ImplicitConversionSequence::StandardConversion:
2451 SCS = &ICS.Standard;
2452 break;
2453 case ImplicitConversionSequence::UserDefinedConversion:
2454 SCS = &ICS.UserDefined.After;
2455 break;
2456 case ImplicitConversionSequence::AmbiguousConversion:
2457 case ImplicitConversionSequence::EllipsisConversion:
2458 case ImplicitConversionSequence::BadConversion:
2459 return false;
2460 }
2461
2462 // Check if SCS represents a narrowing conversion, according to C++0x
2463 // [dcl.init.list]p7:
2464 //
2465 // A narrowing conversion is an implicit conversion ...
2466 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2467 QualType FromType = SCS->getToType(0);
2468 QualType ToType = SCS->getToType(1);
2469 switch (PossibleNarrowing) {
2470 // * from a floating-point type to an integer type, or
2471 //
2472 // * from an integer type or unscoped enumeration type to a floating-point
2473 // type, except where the source is a constant expression and the actual
2474 // value after conversion will fit into the target type and will produce
2475 // the original value when converted back to the original type, or
2476 case ICK_Floating_Integral:
2477 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2478 *isInitializerConstant = false;
2479 return true;
2480 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2481 llvm::APSInt IntConstantValue;
2482 if (Initializer &&
2483 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2484 // Convert the integer to the floating type.
2485 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2486 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2487 llvm::APFloat::rmNearestTiesToEven);
2488 // And back.
2489 llvm::APSInt ConvertedValue = IntConstantValue;
2490 bool ignored;
2491 Result.convertToInteger(ConvertedValue,
2492 llvm::APFloat::rmTowardZero, &ignored);
2493 // If the resulting value is different, this was a narrowing conversion.
2494 if (IntConstantValue != ConvertedValue) {
2495 *isInitializerConstant = true;
2496 *ConstantValue = APValue(IntConstantValue);
2497 return true;
2498 }
2499 } else {
2500 // Variables are always narrowings.
2501 *isInitializerConstant = false;
2502 return true;
2503 }
2504 }
2505 return false;
2506
2507 // * from long double to double or float, or from double to float, except
2508 // where the source is a constant expression and the actual value after
2509 // conversion is within the range of values that can be represented (even
2510 // if it cannot be represented exactly), or
2511 case ICK_Floating_Conversion:
2512 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2513 // FromType is larger than ToType.
2514 Expr::EvalResult InitializerValue;
2515 // FIXME: Check whether Initializer is a constant expression according
2516 // to C++0x [expr.const], rather than just whether it can be folded.
2517 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2518 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2519 // Constant! (Except for FIXME above.)
2520 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2521 // Convert the source value into the target type.
2522 bool ignored;
2523 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2524 Ctx.getFloatTypeSemantics(ToType),
2525 llvm::APFloat::rmNearestTiesToEven, &ignored);
2526 // If there was no overflow, the source value is within the range of
2527 // values that can be represented.
2528 if (ConvertStatus & llvm::APFloat::opOverflow) {
2529 *isInitializerConstant = true;
2530 *ConstantValue = InitializerValue.Val;
2531 return true;
2532 }
2533 } else {
2534 *isInitializerConstant = false;
2535 return true;
2536 }
2537 }
2538 return false;
2539
2540 // * from an integer type or unscoped enumeration type to an integer type
2541 // that cannot represent all the values of the original type, except where
2542 // the source is a constant expression and the actual value after
2543 // conversion will fit into the target type and will produce the original
2544 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002545 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002546 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2547 // Boolean conversions can be from pointers and pointers to members
2548 // [conv.bool], and those aren't considered narrowing conversions.
2549 return false;
2550 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002551 case ICK_Integral_Conversion: {
2552 assert(FromType->isIntegralOrUnscopedEnumerationType());
2553 assert(ToType->isIntegralOrUnscopedEnumerationType());
2554 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2555 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2556 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2557 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2558
2559 if (FromWidth > ToWidth ||
2560 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2561 // Not all values of FromType can be represented in ToType.
2562 llvm::APSInt InitializerValue;
2563 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2564 *isInitializerConstant = true;
2565 *ConstantValue = APValue(InitializerValue);
2566
2567 // Add a bit to the InitializerValue so we don't have to worry about
2568 // signed vs. unsigned comparisons.
2569 InitializerValue = InitializerValue.extend(
2570 InitializerValue.getBitWidth() + 1);
2571 // Convert the initializer to and from the target width and signed-ness.
2572 llvm::APSInt ConvertedValue = InitializerValue;
2573 ConvertedValue = ConvertedValue.trunc(ToWidth);
2574 ConvertedValue.setIsSigned(ToSigned);
2575 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2576 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2577 // If the result is different, this was a narrowing conversion.
2578 return ConvertedValue != InitializerValue;
2579 } else {
2580 // Variables are always narrowings.
2581 *isInitializerConstant = false;
2582 return true;
2583 }
2584 }
2585 return false;
2586 }
2587
2588 default:
2589 // Other kinds of conversions are not narrowings.
2590 return false;
2591 }
2592}
2593
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002594void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002595 FunctionDecl *Function,
2596 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002597 Step S;
2598 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2599 S.Type = Function->getType();
Benjamin Kramerec440992011-10-09 17:58:25 +00002600 S.Function.HadMultipleCandidates = false;
John McCalla0296f72010-03-19 07:35:19 +00002601 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002602 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603 Steps.push_back(S);
2604}
2605
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002607 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002608 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002609 switch (VK) {
2610 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2611 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2612 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002613 default: llvm_unreachable("No such category");
2614 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002615 S.Type = BaseType;
2616 Steps.push_back(S);
2617}
2618
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002620 bool BindingTemporary) {
2621 Step S;
2622 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2623 S.Type = T;
2624 Steps.push_back(S);
2625}
2626
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002627void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2628 Step S;
2629 S.Kind = SK_ExtraneousCopyToTemporary;
2630 S.Type = T;
2631 Steps.push_back(S);
2632}
2633
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002634void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002635 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002636 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002637 Step S;
2638 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002639 S.Type = T;
Benjamin Kramerec440992011-10-09 17:58:25 +00002640 S.Function.HadMultipleCandidates = false;
John McCalla0296f72010-03-19 07:35:19 +00002641 S.Function.Function = Function;
2642 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002643 Steps.push_back(S);
2644}
2645
2646void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002647 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002648 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002649 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002650 switch (VK) {
2651 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002652 S.Kind = SK_QualificationConversionRValue;
2653 break;
John McCall2536c6d2010-08-25 10:28:54 +00002654 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002655 S.Kind = SK_QualificationConversionXValue;
2656 break;
John McCall2536c6d2010-08-25 10:28:54 +00002657 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002658 S.Kind = SK_QualificationConversionLValue;
2659 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002660 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002661 S.Type = Ty;
2662 Steps.push_back(S);
2663}
2664
2665void InitializationSequence::AddConversionSequenceStep(
2666 const ImplicitConversionSequence &ICS,
2667 QualType T) {
2668 Step S;
2669 S.Kind = SK_ConversionSequence;
2670 S.Type = T;
2671 S.ICS = new ImplicitConversionSequence(ICS);
2672 Steps.push_back(S);
2673}
2674
Douglas Gregor51e77d52009-12-10 17:56:55 +00002675void InitializationSequence::AddListInitializationStep(QualType T) {
2676 Step S;
2677 S.Kind = SK_ListInitialization;
2678 S.Type = T;
2679 Steps.push_back(S);
2680}
2681
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002683InitializationSequence::AddConstructorInitializationStep(
2684 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002685 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002686 QualType T) {
2687 Step S;
2688 S.Kind = SK_ConstructorInitialization;
2689 S.Type = T;
Benjamin Kramerec440992011-10-09 17:58:25 +00002690 S.Function.HadMultipleCandidates = false;
John McCalla0296f72010-03-19 07:35:19 +00002691 S.Function.Function = Constructor;
2692 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002693 Steps.push_back(S);
2694}
2695
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002696void InitializationSequence::AddZeroInitializationStep(QualType T) {
2697 Step S;
2698 S.Kind = SK_ZeroInitialization;
2699 S.Type = T;
2700 Steps.push_back(S);
2701}
2702
Douglas Gregore1314a62009-12-18 05:02:21 +00002703void InitializationSequence::AddCAssignmentStep(QualType T) {
2704 Step S;
2705 S.Kind = SK_CAssignment;
2706 S.Type = T;
2707 Steps.push_back(S);
2708}
2709
Eli Friedman78275202009-12-19 08:11:05 +00002710void InitializationSequence::AddStringInitStep(QualType T) {
2711 Step S;
2712 S.Kind = SK_StringInit;
2713 S.Type = T;
2714 Steps.push_back(S);
2715}
2716
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002717void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2718 Step S;
2719 S.Kind = SK_ObjCObjectConversion;
2720 S.Type = T;
2721 Steps.push_back(S);
2722}
2723
Douglas Gregore2f943b2011-02-22 18:29:51 +00002724void InitializationSequence::AddArrayInitStep(QualType T) {
2725 Step S;
2726 S.Kind = SK_ArrayInit;
2727 S.Type = T;
2728 Steps.push_back(S);
2729}
2730
John McCall31168b02011-06-15 23:02:42 +00002731void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2732 bool shouldCopy) {
2733 Step s;
2734 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2735 : SK_PassByIndirectRestore);
2736 s.Type = type;
2737 Steps.push_back(s);
2738}
2739
2740void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2741 Step S;
2742 S.Kind = SK_ProduceObjCObject;
2743 S.Type = T;
2744 Steps.push_back(S);
2745}
2746
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002747void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002748 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002749 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002750 this->Failure = Failure;
2751 this->FailedOverloadResult = Result;
2752}
2753
2754//===----------------------------------------------------------------------===//
2755// Attempt initialization
2756//===----------------------------------------------------------------------===//
2757
John McCall31168b02011-06-15 23:02:42 +00002758static void MaybeProduceObjCObject(Sema &S,
2759 InitializationSequence &Sequence,
2760 const InitializedEntity &Entity) {
2761 if (!S.getLangOptions().ObjCAutoRefCount) return;
2762
2763 /// When initializing a parameter, produce the value if it's marked
2764 /// __attribute__((ns_consumed)).
2765 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2766 if (!Entity.isParameterConsumed())
2767 return;
2768
2769 assert(Entity.getType()->isObjCRetainableType() &&
2770 "consuming an object of unretainable type?");
2771 Sequence.AddProduceObjCObjectStep(Entity.getType());
2772
2773 /// When initializing a return value, if the return type is a
2774 /// retainable type, then returns need to immediately retain the
2775 /// object. If an autorelease is required, it will be done at the
2776 /// last instant.
2777 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2778 if (!Entity.getType()->isObjCRetainableType())
2779 return;
2780
2781 Sequence.AddProduceObjCObjectStep(Entity.getType());
2782 }
2783}
2784
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002785/// \brief Attempt list initialization (C++0x [dcl.init.list])
2786static void TryListInitialization(Sema &S,
2787 const InitializedEntity &Entity,
2788 const InitializationKind &Kind,
2789 InitListExpr *InitList,
2790 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002791 QualType DestType = Entity.getType();
2792
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002793 // C++ doesn't allow scalar initialization with more than one argument.
2794 // But C99 complex numbers are scalars and it makes sense there.
2795 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2796 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2797 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2798 return;
2799 }
2800 // FIXME: C++0x defines behavior for these two cases.
2801 if (DestType->isReferenceType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002802 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2803 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002804 }
2805 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002806 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002807 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002808 }
2809
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002810 InitListChecker CheckInitList(S, Entity, InitList,
2811 DestType, /*VerifyOnly=*/true);
2812 if (CheckInitList.HadError()) {
2813 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2814 return;
2815 }
2816
2817 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002818 Sequence.AddListInitializationStep(DestType);
2819}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002820
2821/// \brief Try a reference initialization that involves calling a conversion
2822/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002823static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2824 const InitializedEntity &Entity,
2825 const InitializationKind &Kind,
2826 Expr *Initializer,
2827 bool AllowRValues,
2828 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002829 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002830 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2831 QualType T1 = cv1T1.getUnqualifiedType();
2832 QualType cv2T2 = Initializer->getType();
2833 QualType T2 = cv2T2.getUnqualifiedType();
2834
2835 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002836 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002837 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002839 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002840 ObjCConversion,
2841 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002842 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002843 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002844 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002845 (void)ObjCLifetimeConversion;
2846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002847 // Build the candidate set directly in the initialization sequence
2848 // structure, so that it will persist if we fail.
2849 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2850 CandidateSet.clear();
2851
2852 // Determine whether we are allowed to call explicit constructors or
2853 // explicit conversion operators.
2854 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002856 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002857 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2858 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002859 // The type we're converting to is a class type. Enumerate its constructors
2860 // to see if there is a suitable conversion.
2861 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002862
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002863 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002864 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002865 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002866 NamedDecl *D = *Con;
2867 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2868
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002869 // Find the constructor (which may be a template).
2870 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002871 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002872 if (ConstructorTmpl)
2873 Constructor = cast<CXXConstructorDecl>(
2874 ConstructorTmpl->getTemplatedDecl());
2875 else
John McCalla0296f72010-03-19 07:35:19 +00002876 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002877
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002878 if (!Constructor->isInvalidDecl() &&
2879 Constructor->isConvertingConstructor(AllowExplicit)) {
2880 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002881 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002882 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002883 &Initializer, 1, CandidateSet,
2884 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002885 else
John McCalla0296f72010-03-19 07:35:19 +00002886 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002887 &Initializer, 1, CandidateSet,
2888 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002891 }
John McCall3696dcb2010-08-17 07:23:57 +00002892 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2893 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002894
Douglas Gregor496e8b342010-05-07 19:42:26 +00002895 const RecordType *T2RecordType = 0;
2896 if ((T2RecordType = T2->getAs<RecordType>()) &&
2897 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002898 // The type we're converting from is a class type, enumerate its conversion
2899 // functions.
2900 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2901
John McCallad371252010-01-20 00:46:10 +00002902 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002903 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002904 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2905 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002906 NamedDecl *D = *I;
2907 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2908 if (isa<UsingShadowDecl>(D))
2909 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002910
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002911 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2912 CXXConversionDecl *Conv;
2913 if (ConvTemplate)
2914 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2915 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002916 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002918 // If the conversion function doesn't return a reference type,
2919 // it can't be considered for this conversion unless we're allowed to
2920 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002921 // FIXME: Do we need to make sure that we only consider conversion
2922 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002923 // break recursion.
2924 if ((AllowExplicit || !Conv->isExplicit()) &&
2925 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2926 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002927 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002928 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002929 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002930 else
John McCalla0296f72010-03-19 07:35:19 +00002931 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002932 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002933 }
2934 }
2935 }
John McCall3696dcb2010-08-17 07:23:57 +00002936 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2937 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002939 SourceLocation DeclLoc = Initializer->getLocStart();
2940
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002942 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002944 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002945 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002946
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002947 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002948
Chandler Carruth30141632011-02-25 19:41:05 +00002949 // This is the overload that will actually be used for the initialization, so
2950 // mark it as used.
2951 S.MarkDeclarationReferenced(DeclLoc, Function);
2952
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002953 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002954 if (isa<CXXConversionDecl>(Function))
2955 T2 = Function->getResultType();
2956 else
2957 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002958
2959 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002960 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002961 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002962
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002964 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002965 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002966 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002967 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002968 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002969 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002970
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002971 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002972 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002973 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002974 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002976 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002977 NewDerivedToBase, NewObjCConversion,
2978 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002979 if (NewRefRelationship == Sema::Ref_Incompatible) {
2980 // If the type we've converted to is not reference-related to the
2981 // type we're looking for, then there is another conversion step
2982 // we need to perform to produce a temporary of the right type
2983 // that we'll be binding to.
2984 ImplicitConversionSequence ICS;
2985 ICS.setStandard();
2986 ICS.Standard = Best->FinalConversion;
2987 T2 = ICS.Standard.getToType(2);
2988 Sequence.AddConversionSequenceStep(ICS, T2);
2989 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002990 Sequence.AddDerivedToBaseCastStep(
2991 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002993 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002994 else if (NewObjCConversion)
2995 Sequence.AddObjCObjectConversionStep(
2996 S.Context.getQualifiedType(T1,
2997 T2.getNonReferenceType().getQualifiers()));
2998
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002999 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003000 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003001
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003002 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3003 return OR_Success;
3004}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005
3006/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3007static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003008 const InitializedEntity &Entity,
3009 const InitializationKind &Kind,
3010 Expr *Initializer,
3011 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003012 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003013 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003014 Qualifiers T1Quals;
3015 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003016 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003017 Qualifiers T2Quals;
3018 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003019 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00003020
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003021 // If the initializer is the address of an overloaded function, try
3022 // to resolve the overloaded function. If all goes well, T2 is the
3023 // type of the resulting function.
3024 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00003025 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003026 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00003027 T1,
3028 false,
3029 Found)) {
3030 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
3031 cv2T2 = Fn->getType();
3032 T2 = cv2T2.getUnqualifiedType();
3033 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003034 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3035 return;
3036 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003037 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003038
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003039 // Compute some basic properties of the types and the initializer.
3040 bool isLValueRef = DestType->isLValueReferenceType();
3041 bool isRValueRef = !isLValueRef;
3042 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003043 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003044 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003045 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003046 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003047 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003048 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003049
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003050 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003052 // "cv2 T2" as follows:
3053 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003055 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003056 // Note the analogous bullet points for rvlaue refs to functions. Because
3057 // there are no function rvalues in C++, rvalue refs to functions are treated
3058 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003059 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003060 bool T1Function = T1->isFunctionType();
3061 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003063 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003065 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003067 // reference-compatible with "cv2 T2," or
3068 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003070 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003071 // can occur. However, we do pay attention to whether it is a bit-field
3072 // to decide whether we're actually binding to a temporary created from
3073 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003074 if (DerivedToBase)
3075 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003077 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003078 else if (ObjCConversion)
3079 Sequence.AddObjCObjectConversionStep(
3080 S.Context.getQualifiedType(T1, T2Quals));
3081
Chandler Carruth04bdce62010-01-12 20:32:25 +00003082 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003083 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003084 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003085 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003086 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003087 return;
3088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089
3090 // - has a class type (i.e., T2 is a class type), where T1 is not
3091 // reference-related to T2, and can be implicitly converted to an
3092 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3093 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003094 // applicable conversion functions (13.3.1.6) and choosing the best
3095 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003096 // If we have an rvalue ref to function type here, the rhs must be
3097 // an rvalue.
3098 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3099 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003101 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003102 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003103 Sequence);
3104 if (ConvOvlResult == OR_Success)
3105 return;
John McCall0d1da222010-01-12 00:44:57 +00003106 if (ConvOvlResult != OR_No_Viable_Function) {
3107 Sequence.SetOverloadFailure(
3108 InitializationSequence::FK_ReferenceInitOverloadFailed,
3109 ConvOvlResult);
3110 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003111 }
3112 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003113
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003115 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003116 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003117 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003118 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3119 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3120 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003121 Sequence.SetOverloadFailure(
3122 InitializationSequence::FK_ReferenceInitOverloadFailed,
3123 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003124 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003125 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003126 ? (RefRelationship == Sema::Ref_Related
3127 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3128 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3129 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003130
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003131 return;
3132 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003133
Douglas Gregor92e460e2011-01-20 16:44:54 +00003134 // - If the initializer expression
3135 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3136 // "cv1 T1" is reference-compatible with "cv2 T2"
3137 // Note: functions are handled below.
3138 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003139 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003141 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003142 (InitCategory.isXValue() ||
3143 (InitCategory.isPRValue() && T2->isRecordType()) ||
3144 (InitCategory.isPRValue() && T2->isArrayType()))) {
3145 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3146 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003147 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3148 // compiler the freedom to perform a copy here or bind to the
3149 // object, while C++0x requires that we bind directly to the
3150 // object. Hence, we always bind to the object without making an
3151 // extra copy. However, in C++03 requires that we check for the
3152 // presence of a suitable copy constructor:
3153 //
3154 // The constructor that would be used to make the copy shall
3155 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003156 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003157 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
Douglas Gregor92e460e2011-01-20 16:44:54 +00003160 if (DerivedToBase)
3161 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3162 ValueKind);
3163 else if (ObjCConversion)
3164 Sequence.AddObjCObjectConversionStep(
3165 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregor92e460e2011-01-20 16:44:54 +00003167 if (T1Quals != T2Quals)
3168 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003169 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00003170 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
3174 // - has a class type (i.e., T2 is a class type), where T1 is not
3175 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003176 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3177 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003178 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179 if (RefRelationship == Sema::Ref_Incompatible) {
3180 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3181 Kind, Initializer,
3182 /*AllowRValues=*/true,
3183 Sequence);
3184 if (ConvOvlResult)
3185 Sequence.SetOverloadFailure(
3186 InitializationSequence::FK_ReferenceInitOverloadFailed,
3187 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003189 return;
3190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003192 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3193 return;
3194 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003195
3196 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003199 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 // Determine whether we are allowed to call explicit constructors or
3202 // explicit conversion operators.
3203 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003204
3205 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3206
John McCall31168b02011-06-15 23:02:42 +00003207 ImplicitConversionSequence ICS
3208 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003209 /*SuppressUserConversions*/ false,
3210 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003211 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003212 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3213 /*AllowObjCWritebackConversion=*/false);
3214
3215 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216 // FIXME: Use the conversion function set stored in ICS to turn
3217 // this into an overloading ambiguity diagnostic. However, we need
3218 // to keep that set as an OverloadCandidateSet rather than as some
3219 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003220 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3221 Sequence.SetOverloadFailure(
3222 InitializationSequence::FK_ReferenceInitOverloadFailed,
3223 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003224 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3225 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003226 else
3227 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228 return;
John McCall31168b02011-06-15 23:02:42 +00003229 } else {
3230 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003231 }
3232
3233 // [...] If T1 is reference-related to T2, cv1 must be the
3234 // same cv-qualification as, or greater cv-qualification
3235 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003236 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3237 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003239 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003240 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3241 return;
3242 }
3243
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003245 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003247 InitCategory.isLValue()) {
3248 Sequence.SetFailed(
3249 InitializationSequence::FK_RValueReferenceBindingToLValue);
3250 return;
3251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003252
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003253 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3254 return;
3255}
3256
3257/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258/// (C++ [dcl.init.string], C99 6.7.8).
3259static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003260 const InitializedEntity &Entity,
3261 const InitializationKind &Kind,
3262 Expr *Initializer,
3263 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003264 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265}
3266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3268/// enumerates the constructors of the initialized entity and performs overload
3269/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003270static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003271 const InitializedEntity &Entity,
3272 const InitializationKind &Kind,
3273 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003274 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003275 InitializationSequence &Sequence) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00003276 // Check constructor arguments for self reference.
3277 if (DeclaratorDecl *DD = Entity.getDecl())
3278 // Parameters arguments are occassionially constructed with itself,
3279 // for instance, in recursive functions. Skip them.
3280 if (!isa<ParmVarDecl>(DD))
3281 for (unsigned i = 0; i < NumArgs; ++i)
3282 S.CheckSelfReference(DD, Args[i]);
3283
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003284 // Build the candidate set directly in the initialization sequence
3285 // structure, so that it will persist if we fail.
3286 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3287 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003289 // Determine whether we are allowed to call explicit constructors or
3290 // explicit conversion operators.
3291 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3292 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003293 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003294
3295 // The type we're constructing needs to be complete.
3296 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003297 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003298 return;
3299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003301 // The type we're converting to is a class type. Enumerate its constructors
3302 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003303 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003305 CXXRecordDecl *DestRecordDecl
3306 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003308 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003309 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003310 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003311 NamedDecl *D = *Con;
3312 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003313 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003315 // Find the constructor (which may be a template).
3316 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003317 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003318 if (ConstructorTmpl)
3319 Constructor = cast<CXXConstructorDecl>(
3320 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003321 else {
John McCalla0296f72010-03-19 07:35:19 +00003322 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003323
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003324 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003325 // suppress user-defined conversions on the arguments.
3326 // FIXME: Move constructors?
3327 if (Kind.getKind() == InitializationKind::IK_Copy &&
3328 Constructor->isCopyConstructor())
3329 SuppressUserConversions = true;
3330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003332 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003333 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003334 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003335 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003336 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003337 Args, NumArgs, CandidateSet,
3338 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003339 else
John McCalla0296f72010-03-19 07:35:19 +00003340 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003341 Args, NumArgs, CandidateSet,
3342 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344 }
3345
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003346 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347
3348 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003349 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003351 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003352 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003354 Result);
3355 return;
3356 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003357
3358 // C++0x [dcl.init]p6:
3359 // If a program calls for the default initialization of an object
3360 // of a const-qualified type T, T shall be a class type with a
3361 // user-provided default constructor.
3362 if (Kind.getKind() == InitializationKind::IK_Default &&
3363 Entity.getType().isConstQualified() &&
3364 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3365 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3366 return;
3367 }
3368
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003369 // Add the constructor initialization step. Any cv-qualification conversion is
3370 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003371 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003373 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003374 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003375}
3376
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003377/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003379 const InitializedEntity &Entity,
3380 const InitializationKind &Kind,
3381 InitializationSequence &Sequence) {
3382 // C++ [dcl.init]p5:
3383 //
3384 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003385 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003387 // -- if T is an array type, then each element is value-initialized;
3388 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3389 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003391 if (const RecordType *RT = T->getAs<RecordType>()) {
3392 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3393 // -- if T is a class type (clause 9) with a user-declared
3394 // constructor (12.1), then the default constructor for T is
3395 // called (and the initialization is ill-formed if T has no
3396 // accessible default constructor);
3397 //
3398 // FIXME: we really want to refer to a single subobject of the array,
3399 // but Entity doesn't have a way to capture that (yet).
3400 if (ClassDecl->hasUserDeclaredConstructor())
3401 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003403 // -- if T is a (possibly cv-qualified) non-union class type
3404 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003405 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003406 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003407 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003408 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003409 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003411 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003412 }
3413 }
3414
Douglas Gregor1b303932009-12-22 15:35:07 +00003415 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003416}
3417
Douglas Gregor85dabae2009-12-16 01:38:02 +00003418/// \brief Attempt default initialization (C++ [dcl.init]p6).
3419static void TryDefaultInitialization(Sema &S,
3420 const InitializedEntity &Entity,
3421 const InitializationKind &Kind,
3422 InitializationSequence &Sequence) {
3423 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424
Douglas Gregor85dabae2009-12-16 01:38:02 +00003425 // C++ [dcl.init]p6:
3426 // To default-initialize an object of type T means:
3427 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003428 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3429
Douglas Gregor85dabae2009-12-16 01:38:02 +00003430 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3431 // constructor for T is called (and the initialization is ill-formed if
3432 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003433 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003434 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3435 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
Douglas Gregor85dabae2009-12-16 01:38:02 +00003438 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregor85dabae2009-12-16 01:38:02 +00003440 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003442 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003443 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003444 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003445 return;
3446 }
3447
3448 // If the destination type has a lifetime property, zero-initialize it.
3449 if (DestType.getQualifiers().hasObjCLifetime()) {
3450 Sequence.AddZeroInitializationStep(Entity.getType());
3451 return;
3452 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003453}
3454
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003455/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3456/// which enumerates all conversion functions and performs overload resolution
3457/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003459 const InitializedEntity &Entity,
3460 const InitializationKind &Kind,
3461 Expr *Initializer,
3462 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003463 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003464 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3465 QualType SourceType = Initializer->getType();
3466 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3467 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Douglas Gregor540c3b02009-12-14 17:27:33 +00003469 // Build the candidate set directly in the initialization sequence
3470 // structure, so that it will persist if we fail.
3471 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3472 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Douglas Gregor540c3b02009-12-14 17:27:33 +00003474 // Determine whether we are allowed to call explicit constructors or
3475 // explicit conversion operators.
3476 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
Douglas Gregor540c3b02009-12-14 17:27:33 +00003478 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3479 // The type we're converting to is a class type. Enumerate its constructors
3480 // to see if there is a suitable conversion.
3481 CXXRecordDecl *DestRecordDecl
3482 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregord9848152010-04-26 14:36:57 +00003484 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003486 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003487 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003488 Con != ConEnd; ++Con) {
3489 NamedDecl *D = *Con;
3490 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
Douglas Gregord9848152010-04-26 14:36:57 +00003492 // Find the constructor (which may be a template).
3493 CXXConstructorDecl *Constructor = 0;
3494 FunctionTemplateDecl *ConstructorTmpl
3495 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003496 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003497 Constructor = cast<CXXConstructorDecl>(
3498 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003499 else
Douglas Gregord9848152010-04-26 14:36:57 +00003500 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregord9848152010-04-26 14:36:57 +00003502 if (!Constructor->isInvalidDecl() &&
3503 Constructor->isConvertingConstructor(AllowExplicit)) {
3504 if (ConstructorTmpl)
3505 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3506 /*ExplicitArgs*/ 0,
3507 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003508 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003509 else
3510 S.AddOverloadCandidate(Constructor, FoundDecl,
3511 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003512 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514 }
Douglas Gregord9848152010-04-26 14:36:57 +00003515 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003516 }
Eli Friedman78275202009-12-19 08:11:05 +00003517
3518 SourceLocation DeclLoc = Initializer->getLocStart();
3519
Douglas Gregor540c3b02009-12-14 17:27:33 +00003520 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3521 // The type we're converting from is a class type, enumerate its conversion
3522 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003523
Eli Friedman4afe9a32009-12-20 22:12:03 +00003524 // We can only enumerate the conversion functions for a complete type; if
3525 // the type isn't complete, simply skip this step.
3526 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3527 CXXRecordDecl *SourceRecordDecl
3528 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
John McCallad371252010-01-20 00:46:10 +00003530 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003531 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003532 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003534 I != E; ++I) {
3535 NamedDecl *D = *I;
3536 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3537 if (isa<UsingShadowDecl>(D))
3538 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539
Eli Friedman4afe9a32009-12-20 22:12:03 +00003540 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3541 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003542 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003543 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003544 else
John McCallda4458e2010-03-31 01:36:47 +00003545 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546
Eli Friedman4afe9a32009-12-20 22:12:03 +00003547 if (AllowExplicit || !Conv->isExplicit()) {
3548 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003549 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003550 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003551 CandidateSet);
3552 else
John McCalla0296f72010-03-19 07:35:19 +00003553 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003554 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003555 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003556 }
3557 }
3558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
3560 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003561 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003562 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003563 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003564 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003566 Result);
3567 return;
3568 }
John McCall0d1da222010-01-12 00:44:57 +00003569
Douglas Gregor540c3b02009-12-14 17:27:33 +00003570 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003571 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregor540c3b02009-12-14 17:27:33 +00003573 if (isa<CXXConstructorDecl>(Function)) {
3574 // Add the user-defined conversion step. Any cv-qualification conversion is
3575 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003576 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003577 return;
3578 }
3579
3580 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003581 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003582 if (ConvType->getAs<RecordType>()) {
3583 // If we're converting to a class type, there may be an copy if
3584 // the resulting temporary object (possible to create an object of
3585 // a base class type). That copy is not a separate conversion, so
3586 // we just make a note of the actual destination type (possibly a
3587 // base class of the type returned by the conversion function) and
3588 // let the user-defined conversion step handle the conversion.
3589 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3590 return;
3591 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003592
Douglas Gregor5ab11652010-04-17 22:01:05 +00003593 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594
Douglas Gregor5ab11652010-04-17 22:01:05 +00003595 // If the conversion following the call to the conversion function
3596 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003597 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3598 Best->FinalConversion.Third) {
3599 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003600 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003601 ICS.Standard = Best->FinalConversion;
3602 Sequence.AddConversionSequenceStep(ICS, DestType);
3603 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604}
3605
John McCall31168b02011-06-15 23:02:42 +00003606/// The non-zero enum values here are indexes into diagnostic alternatives.
3607enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3608
3609/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003610static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3611 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003612 // Skip parens.
3613 e = e->IgnoreParens();
3614
3615 // Skip address-of nodes.
3616 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3617 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003618 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003619
3620 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003621 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3622 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003623 case CK_Dependent:
3624 case CK_BitCast:
3625 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003626 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003627 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003628
3629 case CK_ArrayToPointerDecay:
3630 return IIK_nonscalar;
3631
3632 case CK_NullToPointer:
3633 return IIK_okay;
3634
3635 default:
3636 break;
3637 }
3638
3639 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003640 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3641 if (!isAddressOf) return IIK_nonlocal;
3642
3643 VarDecl *var;
3644 if (isa<DeclRefExpr>(e)) {
3645 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3646 if (!var) return IIK_nonlocal;
3647 } else {
3648 var = cast<BlockDeclRefExpr>(e)->getDecl();
3649 }
3650
3651 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003652
3653 // If we have a conditional operator, check both sides.
3654 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003655 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003656 return iik;
3657
John McCall63f84442011-06-27 23:59:58 +00003658 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003659
3660 // These are never scalar.
3661 } else if (isa<ArraySubscriptExpr>(e)) {
3662 return IIK_nonscalar;
3663
3664 // Otherwise, it needs to be a null pointer constant.
3665 } else {
3666 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3667 ? IIK_okay : IIK_nonlocal);
3668 }
3669
3670 return IIK_nonlocal;
3671}
3672
3673/// Check whether the given expression is a valid operand for an
3674/// indirect copy/restore.
3675static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3676 assert(src->isRValue());
3677
John McCall63f84442011-06-27 23:59:58 +00003678 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003679 if (iik == IIK_okay) return;
3680
3681 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3682 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3683 << src->getSourceRange();
3684}
3685
Douglas Gregore2f943b2011-02-22 18:29:51 +00003686/// \brief Determine whether we have compatible array types for the
3687/// purposes of GNU by-copy array initialization.
3688static bool hasCompatibleArrayTypes(ASTContext &Context,
3689 const ArrayType *Dest,
3690 const ArrayType *Source) {
3691 // If the source and destination array types are equivalent, we're
3692 // done.
3693 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3694 return true;
3695
3696 // Make sure that the element types are the same.
3697 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3698 return false;
3699
3700 // The only mismatch we allow is when the destination is an
3701 // incomplete array type and the source is a constant array type.
3702 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3703}
3704
John McCall31168b02011-06-15 23:02:42 +00003705static bool tryObjCWritebackConversion(Sema &S,
3706 InitializationSequence &Sequence,
3707 const InitializedEntity &Entity,
3708 Expr *Initializer) {
3709 bool ArrayDecay = false;
3710 QualType ArgType = Initializer->getType();
3711 QualType ArgPointee;
3712 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3713 ArrayDecay = true;
3714 ArgPointee = ArgArrayType->getElementType();
3715 ArgType = S.Context.getPointerType(ArgPointee);
3716 }
3717
3718 // Handle write-back conversion.
3719 QualType ConvertedArgType;
3720 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3721 ConvertedArgType))
3722 return false;
3723
3724 // We should copy unless we're passing to an argument explicitly
3725 // marked 'out'.
3726 bool ShouldCopy = true;
3727 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3728 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3729
3730 // Do we need an lvalue conversion?
3731 if (ArrayDecay || Initializer->isGLValue()) {
3732 ImplicitConversionSequence ICS;
3733 ICS.setStandard();
3734 ICS.Standard.setAsIdentityConversion();
3735
3736 QualType ResultType;
3737 if (ArrayDecay) {
3738 ICS.Standard.First = ICK_Array_To_Pointer;
3739 ResultType = S.Context.getPointerType(ArgPointee);
3740 } else {
3741 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3742 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3743 }
3744
3745 Sequence.AddConversionSequenceStep(ICS, ResultType);
3746 }
3747
3748 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3749 return true;
3750}
3751
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752InitializationSequence::InitializationSequence(Sema &S,
3753 const InitializedEntity &Entity,
3754 const InitializationKind &Kind,
3755 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003756 unsigned NumArgs)
3757 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003758 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003760 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 // The semantics of initializers are as follows. The destination type is
3762 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003763 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003765 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003766 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003767
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003768 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003769 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3770 SequenceKind = DependentSequence;
3771 return;
3772 }
3773
Sebastian Redld201edf2011-06-05 13:59:11 +00003774 // Almost everything is a normal sequence.
3775 setSequenceKind(NormalSequence);
3776
John McCalled75c092010-12-07 22:54:16 +00003777 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003778 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3779 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3780 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003781 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003782 return;
3783 }
3784 Args[I] = Result.take();
3785 }
John McCalled75c092010-12-07 22:54:16 +00003786
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003787 QualType SourceType;
3788 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003789 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003790 Initializer = Args[0];
3791 if (!isa<InitListExpr>(Initializer))
3792 SourceType = Initializer->getType();
3793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794
3795 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003796 // list-initialized (8.5.4).
3797 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003798 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003799 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003801
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003802 // - If the destination type is a reference type, see 8.5.3.
3803 if (DestType->isReferenceType()) {
3804 // C++0x [dcl.init.ref]p1:
3805 // A variable declared to be a T& or T&&, that is, "reference to type T"
3806 // (8.3.2), shall be initialized by an object, or function, of type T or
3807 // by an object that can be converted into a T.
3808 // (Therefore, multiple arguments are not permitted.)
3809 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003810 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003811 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003812 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003813 return;
3814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003816 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003817 if (Kind.getKind() == InitializationKind::IK_Value ||
3818 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003819 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 return;
3821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Douglas Gregor85dabae2009-12-16 01:38:02 +00003823 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003824 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003825 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003826 return;
3827 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003828
John McCall66884dd2011-02-21 07:22:22 +00003829 // - If the destination type is an array of characters, an array of
3830 // char16_t, an array of char32_t, or an array of wchar_t, and the
3831 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003833 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003834 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3835 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003836 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003837 return;
3838 }
3839
Douglas Gregore2f943b2011-02-22 18:29:51 +00003840 // Note: as an GNU C extension, we allow initialization of an
3841 // array from a compound literal that creates an array of the same
3842 // type, so long as the initializer has no side effects.
3843 if (!S.getLangOptions().CPlusPlus && Initializer &&
3844 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3845 Initializer->getType()->isArrayType()) {
3846 const ArrayType *SourceAT
3847 = Context.getAsArrayType(Initializer->getType());
3848 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003849 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003850 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003851 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003852 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003853 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003854 }
3855 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003856 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003857 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003858 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003859
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003860 return;
3861 }
Eli Friedman78275202009-12-19 08:11:05 +00003862
John McCall31168b02011-06-15 23:02:42 +00003863 // Determine whether we should consider writeback conversions for
3864 // Objective-C ARC.
3865 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3866 Entity.getKind() == InitializedEntity::EK_Parameter;
3867
3868 // We're at the end of the line for C: it's either a write-back conversion
3869 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003870 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003871 // If allowed, check whether this is an Objective-C writeback conversion.
3872 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003873 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003874 return;
3875 }
3876
3877 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003878 AddCAssignmentStep(DestType);
3879 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003880 return;
3881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882
John McCall31168b02011-06-15 23:02:42 +00003883 assert(S.getLangOptions().CPlusPlus);
3884
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003885 // - If the destination type is a (possibly cv-qualified) class type:
3886 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887 // - If the initialization is direct-initialization, or if it is
3888 // copy-initialization where the cv-unqualified version of the
3889 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003890 // class of the destination, constructors are considered. [...]
3891 if (Kind.getKind() == InitializationKind::IK_Direct ||
3892 (Kind.getKind() == InitializationKind::IK_Copy &&
3893 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3894 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003896 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003898 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 // used) to a derived class thereof are enumerated as described in
3901 // 13.3.1.4, and the best one is chosen through overload resolution
3902 // (13.3).
3903 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003904 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003905 return;
3906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
Douglas Gregor85dabae2009-12-16 01:38:02 +00003908 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003909 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003910 return;
3911 }
3912 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
3914 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003915 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003916 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003917 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3918 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003919 return;
3920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003922 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003923 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003924 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003926 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003927
3928 ImplicitConversionSequence ICS
3929 = S.TryImplicitConversion(Initializer, Entity.getType(),
3930 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003931 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003932 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003933 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3934 allowObjCWritebackConversion);
3935
3936 if (ICS.isStandard() &&
3937 ICS.Standard.Second == ICK_Writeback_Conversion) {
3938 // Objective-C ARC writeback conversion.
3939
3940 // We should copy unless we're passing to an argument explicitly
3941 // marked 'out'.
3942 bool ShouldCopy = true;
3943 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3944 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3945
3946 // If there was an lvalue adjustment, add it as a separate conversion.
3947 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3948 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3949 ImplicitConversionSequence LvalueICS;
3950 LvalueICS.setStandard();
3951 LvalueICS.Standard.setAsIdentityConversion();
3952 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3953 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003954 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003955 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003956
3957 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003958 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003959 DeclAccessPair dap;
3960 if (Initializer->getType() == Context.OverloadTy &&
3961 !S.ResolveAddressOfOverloadedFunction(Initializer
3962 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003963 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003964 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003965 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003966 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003967 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003968
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003969 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003970 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003971}
3972
3973InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003974 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 StepEnd = Steps.end();
3976 Step != StepEnd; ++Step)
3977 Step->Destroy();
3978}
3979
3980//===----------------------------------------------------------------------===//
3981// Perform initialization
3982//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003984getAssignmentAction(const InitializedEntity &Entity) {
3985 switch(Entity.getKind()) {
3986 case InitializedEntity::EK_Variable:
3987 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003988 case InitializedEntity::EK_Exception:
3989 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003990 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003991 return Sema::AA_Initializing;
3992
3993 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003994 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003995 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3996 return Sema::AA_Sending;
3997
Douglas Gregore1314a62009-12-18 05:02:21 +00003998 return Sema::AA_Passing;
3999
4000 case InitializedEntity::EK_Result:
4001 return Sema::AA_Returning;
4002
Douglas Gregore1314a62009-12-18 05:02:21 +00004003 case InitializedEntity::EK_Temporary:
4004 // FIXME: Can we tell apart casting vs. converting?
4005 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006
Douglas Gregore1314a62009-12-18 05:02:21 +00004007 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004008 case InitializedEntity::EK_ArrayElement:
4009 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004010 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004011 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004012 return Sema::AA_Initializing;
4013 }
4014
4015 return Sema::AA_Converting;
4016}
4017
Douglas Gregor95562572010-04-24 23:45:46 +00004018/// \brief Whether we should binding a created object as a temporary when
4019/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004020static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004021 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004022 case InitializedEntity::EK_ArrayElement:
4023 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004024 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004025 case InitializedEntity::EK_New:
4026 case InitializedEntity::EK_Variable:
4027 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004028 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004029 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004030 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004031 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004032 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004033 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034
Douglas Gregore1314a62009-12-18 05:02:21 +00004035 case InitializedEntity::EK_Parameter:
4036 case InitializedEntity::EK_Temporary:
4037 return true;
4038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
Douglas Gregore1314a62009-12-18 05:02:21 +00004040 llvm_unreachable("missed an InitializedEntity kind?");
4041}
4042
Douglas Gregor95562572010-04-24 23:45:46 +00004043/// \brief Whether the given entity, when initialized with an object
4044/// created for that initialization, requires destruction.
4045static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4046 switch (Entity.getKind()) {
4047 case InitializedEntity::EK_Member:
4048 case InitializedEntity::EK_Result:
4049 case InitializedEntity::EK_New:
4050 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004051 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004052 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004053 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004054 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004055 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregor95562572010-04-24 23:45:46 +00004057 case InitializedEntity::EK_Variable:
4058 case InitializedEntity::EK_Parameter:
4059 case InitializedEntity::EK_Temporary:
4060 case InitializedEntity::EK_ArrayElement:
4061 case InitializedEntity::EK_Exception:
4062 return true;
4063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004064
4065 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004066}
4067
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004068/// \brief Make a (potentially elidable) temporary copy of the object
4069/// provided by the given initializer by calling the appropriate copy
4070/// constructor.
4071///
4072/// \param S The Sema object used for type-checking.
4073///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004074/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004075/// the type of the initializer expression or a superclass thereof.
4076///
4077/// \param Enter The entity being initialized.
4078///
4079/// \param CurInit The initializer expression.
4080///
4081/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4082/// is permitted in C++03 (but not C++0x) when binding a reference to
4083/// an rvalue.
4084///
4085/// \returns An expression that copies the initializer expression into
4086/// a temporary object, or an error expression if a copy could not be
4087/// created.
John McCalldadc5752010-08-24 06:29:42 +00004088static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004089 QualType T,
4090 const InitializedEntity &Entity,
4091 ExprResult CurInit,
4092 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004093 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004094 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004096 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004097 Class = cast<CXXRecordDecl>(Record->getDecl());
4098 if (!Class)
4099 return move(CurInit);
4100
Douglas Gregor5d369002011-01-21 18:05:27 +00004101 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004102 // When certain criteria are met, an implementation is allowed to
4103 // omit the copy/move construction of a class object, even if the
4104 // copy/move constructor and/or destructor for the object have
4105 // side effects. [...]
4106 // - when a temporary class object that has not been bound to a
4107 // reference (12.2) would be copied/moved to a class object
4108 // with the same cv-unqualified type, the copy/move operation
4109 // can be omitted by constructing the temporary object
4110 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004112 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004113 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004115 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004116 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004117 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00004118 switch (Entity.getKind()) {
4119 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004120 Loc = Entity.getReturnLoc();
4121 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregore1314a62009-12-18 05:02:21 +00004123 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00004124 Loc = Entity.getThrowLoc();
4125 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Douglas Gregore1314a62009-12-18 05:02:21 +00004127 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00004128 Loc = Entity.getDecl()->getLocation();
4129 break;
4130
Anders Carlsson0bd52402010-01-24 00:19:41 +00004131 case InitializedEntity::EK_ArrayElement:
4132 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00004133 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00004134 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004135 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00004136 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004137 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004138 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004139 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004140 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004141 Loc = CurInitExpr->getLocStart();
4142 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00004143 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00004144
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004146 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4147 return move(CurInit);
4148
Douglas Gregorf282a762011-01-21 19:38:21 +00004149 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00004150 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00004151 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00004152 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004153 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004154 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00004155 // C++0x [dcl.init]p16, second bullet to class types, this
4156 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004157 CXXConstructorDecl *Constructor = 0;
4158
4159 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004160 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004161 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00004162 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00004163 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004164 continue;
4165
4166 DeclAccessPair FoundDecl
4167 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4168 S.AddOverloadCandidate(Constructor, FoundDecl,
4169 &CurInitExpr, 1, CandidateSet);
4170 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004172
4173 // Handle constructor templates.
4174 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4175 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00004176 continue;
John McCalla0296f72010-03-19 07:35:19 +00004177
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004178 Constructor = cast<CXXConstructorDecl>(
4179 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00004180 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004181 continue;
4182
4183 // FIXME: Do we need to limit this to copy-constructor-like
4184 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00004185 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004186 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4187 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4188 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004191 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4192
Douglas Gregore1314a62009-12-18 05:02:21 +00004193 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004194 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004195 case OR_Success:
4196 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregore1314a62009-12-18 05:02:21 +00004198 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004199 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4200 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4201 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004202 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004203 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004204 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004205 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004206 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004207 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregore1314a62009-12-18 05:02:21 +00004209 case OR_Ambiguous:
4210 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004211 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004212 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004213 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004214 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215
Douglas Gregore1314a62009-12-18 05:02:21 +00004216 case OR_Deleted:
4217 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004218 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004219 << CurInitExpr->getSourceRange();
4220 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004221 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004222 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004223 }
4224
Douglas Gregor5ab11652010-04-17 22:01:05 +00004225 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004226 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004227 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004228
Anders Carlssona01874b2010-04-21 18:47:17 +00004229 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004230 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004231
4232 if (IsExtraneousCopy) {
4233 // If this is a totally extraneous copy for C++03 reference
4234 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004235 // expression. We don't generate an (elided) copy operation here
4236 // because doing so would require us to pass down a flag to avoid
4237 // infinite recursion, where each step adds another extraneous,
4238 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004239
Douglas Gregor30b52772010-04-18 07:57:34 +00004240 // Instantiate the default arguments of any extra parameters in
4241 // the selected copy constructor, as if we were going to create a
4242 // proper call to the copy constructor.
4243 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4244 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4245 if (S.RequireCompleteType(Loc, Parm->getType(),
4246 S.PDiag(diag::err_call_incomplete_argument)))
4247 break;
4248
4249 // Build the default argument expression; we don't actually care
4250 // if this succeeds or not, because this routine will complain
4251 // if there was a problem.
4252 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4253 }
4254
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004255 return S.Owned(CurInitExpr);
4256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Chandler Carruth30141632011-02-25 19:41:05 +00004258 S.MarkDeclarationReferenced(Loc, Constructor);
4259
Douglas Gregor5ab11652010-04-17 22:01:05 +00004260 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004261 // constructor call (we might have derived-to-base conversions, or
4262 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004263 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004264 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004265 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004266
Douglas Gregord0ace022010-04-25 00:55:24 +00004267 // Actually perform the constructor call.
4268 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004269 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004270 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004271 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004272 CXXConstructExpr::CK_Complete,
4273 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274
Douglas Gregord0ace022010-04-25 00:55:24 +00004275 // If we're supposed to bind temporaries, do so.
4276 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4277 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4278 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004279}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004281void InitializationSequence::PrintInitLocationNote(Sema &S,
4282 const InitializedEntity &Entity) {
4283 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4284 if (Entity.getDecl()->getLocation().isInvalid())
4285 return;
4286
4287 if (Entity.getDecl()->getDeclName())
4288 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4289 << Entity.getDecl()->getDeclName();
4290 else
4291 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4292 }
4293}
4294
Sebastian Redl112aa822011-07-14 19:07:55 +00004295static bool isReferenceBinding(const InitializationSequence::Step &s) {
4296 return s.Kind == InitializationSequence::SK_BindReference ||
4297 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4298}
4299
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004301InitializationSequence::Perform(Sema &S,
4302 const InitializedEntity &Entity,
4303 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004304 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004305 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004306 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004307 unsigned NumArgs = Args.size();
4308 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004309 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311
Sebastian Redld201edf2011-06-05 13:59:11 +00004312 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004313 // If the declaration is a non-dependent, incomplete array type
4314 // that has an initializer, then its type will be completed once
4315 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004316 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004317 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004318 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004319 if (const IncompleteArrayType *ArrayT
4320 = S.Context.getAsIncompleteArrayType(DeclType)) {
4321 // FIXME: We don't currently have the ability to accurately
4322 // compute the length of an initializer list without
4323 // performing full type-checking of the initializer list
4324 // (since we have to determine where braces are implicitly
4325 // introduced and such). So, we fall back to making the array
4326 // type a dependently-sized array type with no specified
4327 // bound.
4328 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4329 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004330
Douglas Gregor51e77d52009-12-10 17:56:55 +00004331 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004332 if (DeclaratorDecl *DD = Entity.getDecl()) {
4333 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4334 TypeLoc TL = TInfo->getTypeLoc();
4335 if (IncompleteArrayTypeLoc *ArrayLoc
4336 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4337 Brackets = ArrayLoc->getBracketsRange();
4338 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004339 }
4340
4341 *ResultType
4342 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4343 /*NumElts=*/0,
4344 ArrayT->getSizeModifier(),
4345 ArrayT->getIndexTypeCVRQualifiers(),
4346 Brackets);
4347 }
4348
4349 }
4350 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004351 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4352 Kind.isExplicitCast());
4353 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004354 }
4355
Sebastian Redld201edf2011-06-05 13:59:11 +00004356 // No steps means no initialization.
4357 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004358 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359
Douglas Gregor1b303932009-12-22 15:35:07 +00004360 QualType DestType = Entity.getType().getNonReferenceType();
4361 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004362 // the same as Entity.getDecl()->getType() in cases involving type merging,
4363 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004364 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004365 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004366 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004367
John McCalldadc5752010-08-24 06:29:42 +00004368 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004371 // grab the only argument out the Args and place it into the "current"
4372 // initializer.
4373 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004374 case SK_ResolveAddressOfOverloadedFunction:
4375 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004376 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004377 case SK_CastDerivedToBaseLValue:
4378 case SK_BindReference:
4379 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004380 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004381 case SK_UserConversion:
4382 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004383 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004384 case SK_QualificationConversionRValue:
4385 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004386 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004387 case SK_ListInitialization:
4388 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004389 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004390 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004391 case SK_ArrayInit:
4392 case SK_PassByIndirectCopyRestore:
4393 case SK_PassByIndirectRestore:
4394 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004395 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004396 CurInit = Args.get()[0];
4397 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004398
4399 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004400 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4401 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4402 if (CurInit.isInvalid())
4403 return ExprError();
4404 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004405 break;
John McCall34376a62010-12-04 03:47:34 +00004406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407
Douglas Gregore1314a62009-12-18 05:02:21 +00004408 case SK_ConstructorInitialization:
4409 case SK_ZeroInitialization:
4410 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
4413 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004414 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004415 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004416 for (step_iterator Step = step_begin(), StepEnd = step_end();
4417 Step != StepEnd; ++Step) {
4418 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004419 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
John Wiegley01296292011-04-08 18:41:53 +00004421 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004423 switch (Step->Kind) {
4424 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004426 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004427 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004428 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004429 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004430 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004431 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004432 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004434 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004435 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004436 case SK_CastDerivedToBaseLValue: {
4437 // We have a derived-to-base cast that produces either an rvalue or an
4438 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
John McCallcf142162010-08-07 06:22:56 +00004440 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004441
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004442 // Casts to inaccessible base classes are allowed with C-style casts.
4443 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4444 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004445 CurInit.get()->getLocStart(),
4446 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004447 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004448 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Douglas Gregor88d292c2010-05-13 16:44:06 +00004450 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4451 QualType T = SourceType;
4452 if (const PointerType *Pointer = T->getAs<PointerType>())
4453 T = Pointer->getPointeeType();
4454 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004455 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004456 cast<CXXRecordDecl>(RecordTy->getDecl()));
4457 }
4458
John McCall2536c6d2010-08-25 10:28:54 +00004459 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004460 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004461 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004462 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004463 VK_XValue :
4464 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004465 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4466 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004467 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004468 CurInit.get(),
4469 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004470 break;
4471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004473 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004474 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4476 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004477 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004478 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004479 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004480 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004481 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004482 }
Anders Carlssona91be642010-01-29 02:47:33 +00004483
John Wiegley01296292011-04-08 18:41:53 +00004484 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004485 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004486 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4487 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004488 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004489 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004490 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004493 // Reference binding does not have any corresponding ASTs.
4494
4495 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004496 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004497 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004499 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004500
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004501 case SK_BindReferenceToTemporary:
4502 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004503 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004504 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004505
Douglas Gregorfe314812011-06-21 17:03:29 +00004506 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004507 CurInit = new (S.Context) MaterializeTemporaryExpr(
4508 Entity.getType().getNonReferenceType(),
4509 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004510 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004511
4512 // If we're binding to an Objective-C object that has lifetime, we
4513 // need cleanups.
4514 if (S.getLangOptions().ObjCAutoRefCount &&
4515 CurInit.get()->getType()->isObjCLifetimeType())
4516 S.ExprNeedsCleanups = true;
4517
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004518 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004520 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004522 /*IsExtraneousCopy=*/true);
4523 break;
4524
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004525 case SK_UserConversion: {
4526 // We have a user-defined conversion that invokes either a constructor
4527 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004528 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004529 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004530 FunctionDecl *Fn = Step->Function.Function;
4531 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004532 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004533 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004534 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004535 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004536 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004537 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004538 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004539
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004540 // Determine the arguments required to actually perform the constructor
4541 // call.
John Wiegley01296292011-04-08 18:41:53 +00004542 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004544 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004545 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004546 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004548 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004549 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004550 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004551 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004552 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004553 CXXConstructExpr::CK_Complete,
4554 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004555 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004556 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004557
Anders Carlssona01874b2010-04-21 18:47:17 +00004558 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004559 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004560 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561
John McCalle3027922010-08-25 11:45:40 +00004562 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004563 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4564 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4565 S.IsDerivedFrom(SourceType, Class))
4566 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567
Douglas Gregor95562572010-04-24 23:45:46 +00004568 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004569 } else {
4570 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004571 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004572 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004573 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004574 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
4576 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004577 // derived-to-base conversion? I believe the answer is "no", because
4578 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004579 ExprResult CurInitExprRes =
4580 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4581 FoundFn, Conversion);
4582 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004583 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004584 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004586 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004587 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4588 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004589 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004590 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
John McCalle3027922010-08-25 11:45:40 +00004592 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593
Douglas Gregor95562572010-04-24 23:45:46 +00004594 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596
Sebastian Redl112aa822011-07-14 19:07:55 +00004597 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004598 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004599 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004600 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004601 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004602 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004604 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004605 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004606 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004607 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4608 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004609 }
4610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611
John McCallcf142162010-08-07 06:22:56 +00004612 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004613 CurInit.get()->getType(),
4614 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004615 CurInit.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004617 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004618 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4619 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004621 break;
4622 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004624 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004625 case SK_QualificationConversionXValue:
4626 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004627 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004628 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004629 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004630 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004631 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004632 VK_XValue :
4633 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004634 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004635 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004636 }
4637
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004638 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004639 Sema::CheckedConversionKind CCK
4640 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4641 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4642 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4643 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004644 ExprResult CurInitExprRes =
4645 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004646 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004647 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004648 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004649 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004650 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652
Douglas Gregor51e77d52009-12-10 17:56:55 +00004653 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004654 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004655 QualType Ty = Step->Type;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004656 InitListChecker PerformInitList(S, Entity, InitList,
4657 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4658 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004659 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004660
4661 CurInit.release();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004662 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004663 break;
4664 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004665
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004666 case SK_ListConstructorCall:
4667 assert(false && "List constructor calls not yet supported.");
4668
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004669 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004670 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004671 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004672 = cast<CXXConstructorDecl>(Step->Function.Function);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004673 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004675 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004676 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004677 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4678 ? Kind.getEqualLoc()
4679 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004680
4681 if (Kind.getKind() == InitializationKind::IK_Default) {
4682 // Force even a trivial, implicit default constructor to be
4683 // semantically checked. We do this explicitly because we don't build
4684 // the definition for completely trivial constructors.
4685 CXXRecordDecl *ClassDecl = Constructor->getParent();
4686 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004687 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004688 ClassDecl->hasTrivialDefaultConstructor() &&
4689 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004690 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4691 }
4692
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004693 // Determine the arguments required to actually perform the constructor
4694 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004696 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004697 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004698
4699
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004700 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004701 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004702 (Kind.getKind() == InitializationKind::IK_Direct ||
4703 Kind.getKind() == InitializationKind::IK_Value)) {
4704 // An explicitly-constructed temporary, e.g., X(1, 2).
4705 unsigned NumExprs = ConstructorArgs.size();
4706 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004707 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004708 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709
Douglas Gregor2b88c112010-09-08 00:15:04 +00004710 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4711 if (!TSInfo)
4712 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004714 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4715 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004716 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004718 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004719 Kind.getParenRange(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004720 HadMultipleCandidates,
Douglas Gregor199db362010-04-27 20:36:09 +00004721 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004722 } else {
4723 CXXConstructExpr::ConstructionKind ConstructKind =
4724 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004726 if (Entity.getKind() == InitializedEntity::EK_Base) {
4727 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004729 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004730 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004731 ConstructKind = CXXConstructExpr::CK_Delegating;
4732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733
Chandler Carruth01718152010-10-25 08:47:36 +00004734 // Only get the parenthesis range if it is a direct construction.
4735 SourceRange parenRange =
4736 Kind.getKind() == InitializationKind::IK_Direct ?
4737 Kind.getParenRange() : SourceRange();
4738
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004739 // If the entity allows NRVO, mark the construction as elidable
4740 // unconditionally.
4741 if (Entity.allowsNRVO())
4742 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4743 Constructor, /*Elidable=*/true,
4744 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004745 HadMultipleCandidates,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004746 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004747 ConstructKind,
4748 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004749 else
4750 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004752 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004753 HadMultipleCandidates,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004754 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004755 ConstructKind,
4756 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004757 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004758 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004759 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004760
4761 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004762 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004763 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004764 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004766 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004767 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004769 break;
4770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004772 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004773 step_iterator NextStep = Step;
4774 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004776 NextStep->Kind == SK_ConstructorInitialization) {
4777 // The need for zero-initialization is recorded directly into
4778 // the call to the object's constructor within the next step.
4779 ConstructorInitRequiresZeroInit = true;
4780 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4781 S.getLangOptions().CPlusPlus &&
4782 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004783 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4784 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004786 Kind.getRange().getBegin());
4787
4788 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4789 TSInfo->getType().getNonLValueExprType(S.Context),
4790 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004791 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004792 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004793 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004794 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004795 break;
4796 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004797
4798 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004799 QualType SourceType = CurInit.get()->getType();
4800 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004801 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004802 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4803 if (Result.isInvalid())
4804 return ExprError();
4805 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004806
4807 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004808 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004809 if (ConvTy != Sema::Compatible &&
4810 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004811 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004812 == Sema::Compatible)
4813 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004814 if (CurInitExprRes.isInvalid())
4815 return ExprError();
4816 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004817
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004818 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004819 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4820 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004821 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004822 getAssignmentAction(Entity),
4823 &Complained)) {
4824 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004825 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004826 } else if (Complained)
4827 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004828 break;
4829 }
Eli Friedman78275202009-12-19 08:11:05 +00004830
4831 case SK_StringInit: {
4832 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004833 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004834 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004835 break;
4836 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004837
4838 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004839 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004840 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004841 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004842 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004843
4844 case SK_ArrayInit:
4845 // Okay: we checked everything before creating this step. Note that
4846 // this is a GNU extension.
4847 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004848 << Step->Type << CurInit.get()->getType()
4849 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004850
4851 // If the destination type is an incomplete array type, update the
4852 // type accordingly.
4853 if (ResultType) {
4854 if (const IncompleteArrayType *IncompleteDest
4855 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4856 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004857 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004858 *ResultType = S.Context.getConstantArrayType(
4859 IncompleteDest->getElementType(),
4860 ConstantSource->getSize(),
4861 ArrayType::Normal, 0);
4862 }
4863 }
4864 }
John McCall31168b02011-06-15 23:02:42 +00004865 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004866
John McCall31168b02011-06-15 23:02:42 +00004867 case SK_PassByIndirectCopyRestore:
4868 case SK_PassByIndirectRestore:
4869 checkIndirectCopyRestoreSource(S, CurInit.get());
4870 CurInit = S.Owned(new (S.Context)
4871 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4872 Step->Kind == SK_PassByIndirectCopyRestore));
4873 break;
4874
4875 case SK_ProduceObjCObject:
4876 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00004877 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00004878 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004879 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004880 }
4881 }
John McCall1f425642010-11-11 03:21:53 +00004882
4883 // Diagnose non-fatal problems with the completed initialization.
4884 if (Entity.getKind() == InitializedEntity::EK_Member &&
4885 cast<FieldDecl>(Entity.getDecl())->isBitField())
4886 S.CheckBitFieldInitialization(Kind.getLocation(),
4887 cast<FieldDecl>(Entity.getDecl()),
4888 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004890 return move(CurInit);
4891}
4892
4893//===----------------------------------------------------------------------===//
4894// Diagnose initialization failures
4895//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897 const InitializedEntity &Entity,
4898 const InitializationKind &Kind,
4899 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004900 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004901 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902
Douglas Gregor1b303932009-12-22 15:35:07 +00004903 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004904 switch (Failure) {
4905 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004906 // FIXME: Customize for the initialized entity?
4907 if (NumArgs == 0)
4908 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4909 << DestType.getNonReferenceType();
4910 else // FIXME: diagnostic below could be better!
4911 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4912 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004913 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004915 case FK_ArrayNeedsInitList:
4916 case FK_ArrayNeedsInitListOrStringLiteral:
4917 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4918 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4919 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920
Douglas Gregore2f943b2011-02-22 18:29:51 +00004921 case FK_ArrayTypeMismatch:
4922 case FK_NonConstantArrayInit:
4923 S.Diag(Kind.getLocation(),
4924 (Failure == FK_ArrayTypeMismatch
4925 ? diag::err_array_init_different_type
4926 : diag::err_array_init_non_constant_array))
4927 << DestType.getNonReferenceType()
4928 << Args[0]->getType()
4929 << Args[0]->getSourceRange();
4930 break;
4931
John McCall16df1e52010-03-30 21:47:33 +00004932 case FK_AddressOfOverloadFailed: {
4933 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004935 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004936 true,
4937 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004938 break;
John McCall16df1e52010-03-30 21:47:33 +00004939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004941 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004942 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004943 switch (FailedOverloadResult) {
4944 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004945 if (Failure == FK_UserConversionOverloadFailed)
4946 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4947 << Args[0]->getType() << DestType
4948 << Args[0]->getSourceRange();
4949 else
4950 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4951 << DestType << Args[0]->getType()
4952 << Args[0]->getSourceRange();
4953
John McCall5c32be02010-08-24 20:38:10 +00004954 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004955 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004957 case OR_No_Viable_Function:
4958 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4959 << Args[0]->getType() << DestType.getNonReferenceType()
4960 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004961 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004962 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004964 case OR_Deleted: {
4965 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4966 << Args[0]->getType() << DestType.getNonReferenceType()
4967 << Args[0]->getSourceRange();
4968 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004969 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004970 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4971 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004972 if (Ovl == OR_Deleted) {
4973 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004974 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004975 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004976 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004977 }
4978 break;
4979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004981 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004982 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004983 break;
4984 }
4985 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004987 case FK_NonConstLValueReferenceBindingToTemporary:
4988 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004990 Failure == FK_NonConstLValueReferenceBindingToTemporary
4991 ? diag::err_lvalue_reference_bind_to_temporary
4992 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004993 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004994 << DestType.getNonReferenceType()
4995 << Args[0]->getType()
4996 << Args[0]->getSourceRange();
4997 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004999 case FK_RValueReferenceBindingToLValue:
5000 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005001 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005002 << Args[0]->getSourceRange();
5003 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005005 case FK_ReferenceInitDropsQualifiers:
5006 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5007 << DestType.getNonReferenceType()
5008 << Args[0]->getType()
5009 << Args[0]->getSourceRange();
5010 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005012 case FK_ReferenceInitFailed:
5013 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5014 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005015 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005016 << Args[0]->getType()
5017 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005018 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5019 Args[0]->getType()->isObjCObjectPointerType())
5020 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Douglas Gregorb491ed32011-02-19 21:32:49 +00005023 case FK_ConversionFailed: {
5024 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00005025 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
5026 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005027 << DestType
John McCall086a4642010-11-24 05:12:34 +00005028 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005029 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005030 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005031 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5032 Args[0]->getType()->isObjCObjectPointerType())
5033 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005034 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005035 }
John Wiegley01296292011-04-08 18:41:53 +00005036
5037 case FK_ConversionFromPropertyFailed:
5038 // No-op. This error has already been reported.
5039 break;
5040
Douglas Gregor51e77d52009-12-10 17:56:55 +00005041 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005042 SourceRange R;
5043
5044 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005045 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005046 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005048 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005049
Douglas Gregor8ec51732010-09-08 21:40:08 +00005050 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5051 if (Kind.isCStyleOrFunctionalCast())
5052 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5053 << R;
5054 else
5055 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5056 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005057 break;
5058 }
5059
5060 case FK_ReferenceBindingToInitList:
5061 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5062 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5063 break;
5064
5065 case FK_InitListBadDestinationType:
5066 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5067 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5068 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005070 case FK_ConstructorOverloadFailed: {
5071 SourceRange ArgsRange;
5072 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005074 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005076 // FIXME: Using "DestType" for the entity we're printing is probably
5077 // bad.
5078 switch (FailedOverloadResult) {
5079 case OR_Ambiguous:
5080 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5081 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005082 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5083 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005084 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005086 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005087 if (Kind.getKind() == InitializationKind::IK_Default &&
5088 (Entity.getKind() == InitializedEntity::EK_Base ||
5089 Entity.getKind() == InitializedEntity::EK_Member) &&
5090 isa<CXXConstructorDecl>(S.CurContext)) {
5091 // This is implicit default initialization of a member or
5092 // base within a constructor. If no viable function was
5093 // found, notify the user that she needs to explicitly
5094 // initialize this base/member.
5095 CXXConstructorDecl *Constructor
5096 = cast<CXXConstructorDecl>(S.CurContext);
5097 if (Entity.getKind() == InitializedEntity::EK_Base) {
5098 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5099 << Constructor->isImplicit()
5100 << S.Context.getTypeDeclType(Constructor->getParent())
5101 << /*base=*/0
5102 << Entity.getType();
5103
5104 RecordDecl *BaseDecl
5105 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5106 ->getDecl();
5107 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5108 << S.Context.getTagDeclType(BaseDecl);
5109 } else {
5110 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5111 << Constructor->isImplicit()
5112 << S.Context.getTypeDeclType(Constructor->getParent())
5113 << /*member=*/1
5114 << Entity.getName();
5115 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5116
5117 if (const RecordType *Record
5118 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005120 diag::note_previous_decl)
5121 << S.Context.getTagDeclType(Record->getDecl());
5122 }
5123 break;
5124 }
5125
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005126 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5127 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005128 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005129 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005131 case OR_Deleted: {
5132 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5133 << true << DestType << ArgsRange;
5134 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005135 OverloadingResult Ovl
5136 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005137 if (Ovl == OR_Deleted) {
5138 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005139 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005140 } else {
5141 llvm_unreachable("Inconsistent overload resolution?");
5142 }
5143 break;
5144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005145
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005146 case OR_Success:
5147 llvm_unreachable("Conversion did not fail!");
5148 break;
5149 }
5150 break;
5151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Douglas Gregor85dabae2009-12-16 01:38:02 +00005153 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005154 if (Entity.getKind() == InitializedEntity::EK_Member &&
5155 isa<CXXConstructorDecl>(S.CurContext)) {
5156 // This is implicit default-initialization of a const member in
5157 // a constructor. Complain that it needs to be explicitly
5158 // initialized.
5159 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5160 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5161 << Constructor->isImplicit()
5162 << S.Context.getTypeDeclType(Constructor->getParent())
5163 << /*const=*/1
5164 << Entity.getName();
5165 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5166 << Entity.getName();
5167 } else {
5168 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5169 << DestType << (bool)DestType->getAs<RecordType>();
5170 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005171 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005172
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005173 case FK_Incomplete:
5174 S.RequireCompleteType(Kind.getLocation(), DestType,
5175 diag::err_init_incomplete_type);
5176 break;
5177
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005178 case FK_ListInitializationFailed: {
5179 // Run the init list checker again to emit diagnostics.
5180 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5181 QualType DestType = Entity.getType();
5182 InitListChecker DiagnoseInitList(S, Entity, InitList,
5183 DestType, /*VerifyOnly=*/false);
5184 assert(DiagnoseInitList.HadError() &&
5185 "Inconsistent init list check result.");
5186 break;
5187 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005190 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005191 return true;
5192}
Douglas Gregore1314a62009-12-18 05:02:21 +00005193
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005194void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005195 switch (SequenceKind) {
5196 case FailedSequence: {
5197 OS << "Failed sequence: ";
5198 switch (Failure) {
5199 case FK_TooManyInitsForReference:
5200 OS << "too many initializers for reference";
5201 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005202
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005203 case FK_ArrayNeedsInitList:
5204 OS << "array requires initializer list";
5205 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005207 case FK_ArrayNeedsInitListOrStringLiteral:
5208 OS << "array requires initializer list or string literal";
5209 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005210
Douglas Gregore2f943b2011-02-22 18:29:51 +00005211 case FK_ArrayTypeMismatch:
5212 OS << "array type mismatch";
5213 break;
5214
5215 case FK_NonConstantArrayInit:
5216 OS << "non-constant array initializer";
5217 break;
5218
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005219 case FK_AddressOfOverloadFailed:
5220 OS << "address of overloaded function failed";
5221 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005222
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005223 case FK_ReferenceInitOverloadFailed:
5224 OS << "overload resolution for reference initialization failed";
5225 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005227 case FK_NonConstLValueReferenceBindingToTemporary:
5228 OS << "non-const lvalue reference bound to temporary";
5229 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005231 case FK_NonConstLValueReferenceBindingToUnrelated:
5232 OS << "non-const lvalue reference bound to unrelated type";
5233 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005234
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005235 case FK_RValueReferenceBindingToLValue:
5236 OS << "rvalue reference bound to an lvalue";
5237 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005238
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005239 case FK_ReferenceInitDropsQualifiers:
5240 OS << "reference initialization drops qualifiers";
5241 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005243 case FK_ReferenceInitFailed:
5244 OS << "reference initialization failed";
5245 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005246
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005247 case FK_ConversionFailed:
5248 OS << "conversion failed";
5249 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250
John Wiegley01296292011-04-08 18:41:53 +00005251 case FK_ConversionFromPropertyFailed:
5252 OS << "conversion from property failed";
5253 break;
5254
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005255 case FK_TooManyInitsForScalar:
5256 OS << "too many initializers for scalar";
5257 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005259 case FK_ReferenceBindingToInitList:
5260 OS << "referencing binding to initializer list";
5261 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005263 case FK_InitListBadDestinationType:
5264 OS << "initializer list for non-aggregate, non-scalar type";
5265 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005266
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005267 case FK_UserConversionOverloadFailed:
5268 OS << "overloading failed for user-defined conversion";
5269 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005270
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005271 case FK_ConstructorOverloadFailed:
5272 OS << "constructor overloading failed";
5273 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005275 case FK_DefaultInitOfConst:
5276 OS << "default initialization of a const variable";
5277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005279 case FK_Incomplete:
5280 OS << "initialization of incomplete type";
5281 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005282
5283 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005284 OS << "list initialization checker failure";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005286 OS << '\n';
5287 return;
5288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005289
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005290 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005291 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005292 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005293
Sebastian Redld201edf2011-06-05 13:59:11 +00005294 case NormalSequence:
5295 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005296 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005298
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005299 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5300 if (S != step_begin()) {
5301 OS << " -> ";
5302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005304 switch (S->Kind) {
5305 case SK_ResolveAddressOfOverloadedFunction:
5306 OS << "resolve address of overloaded function";
5307 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005308
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005309 case SK_CastDerivedToBaseRValue:
5310 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5311 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005313 case SK_CastDerivedToBaseXValue:
5314 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5315 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005317 case SK_CastDerivedToBaseLValue:
5318 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5319 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005320
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005321 case SK_BindReference:
5322 OS << "bind reference to lvalue";
5323 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005324
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005325 case SK_BindReferenceToTemporary:
5326 OS << "bind reference to a temporary";
5327 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005329 case SK_ExtraneousCopyToTemporary:
5330 OS << "extraneous C++03 copy to temporary";
5331 break;
5332
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005333 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005334 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005335 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005336
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005337 case SK_QualificationConversionRValue:
5338 OS << "qualification conversion (rvalue)";
5339
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005340 case SK_QualificationConversionXValue:
5341 OS << "qualification conversion (xvalue)";
5342
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005343 case SK_QualificationConversionLValue:
5344 OS << "qualification conversion (lvalue)";
5345 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005347 case SK_ConversionSequence:
5348 OS << "implicit conversion sequence (";
5349 S->ICS->DebugPrint(); // FIXME: use OS
5350 OS << ")";
5351 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005353 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005354 OS << "list aggregate initialization";
5355 break;
5356
5357 case SK_ListConstructorCall:
5358 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005359 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005360
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005361 case SK_ConstructorInitialization:
5362 OS << "constructor initialization";
5363 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005364
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005365 case SK_ZeroInitialization:
5366 OS << "zero initialization";
5367 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005369 case SK_CAssignment:
5370 OS << "C assignment";
5371 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005373 case SK_StringInit:
5374 OS << "string initialization";
5375 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005376
5377 case SK_ObjCObjectConversion:
5378 OS << "Objective-C object conversion";
5379 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005380
5381 case SK_ArrayInit:
5382 OS << "array initialization";
5383 break;
John McCall31168b02011-06-15 23:02:42 +00005384
5385 case SK_PassByIndirectCopyRestore:
5386 OS << "pass by indirect copy and restore";
5387 break;
5388
5389 case SK_PassByIndirectRestore:
5390 OS << "pass by indirect restore";
5391 break;
5392
5393 case SK_ProduceObjCObject:
5394 OS << "Objective-C object retension";
5395 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005396 }
5397 }
5398}
5399
5400void InitializationSequence::dump() const {
5401 dump(llvm::errs());
5402}
5403
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005404static void DiagnoseNarrowingInInitList(
5405 Sema& S, QualType EntityType, const Expr *InitE,
5406 bool Constant, const APValue &ConstantValue) {
5407 if (Constant) {
5408 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005409 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005410 ? diag::err_init_list_constant_narrowing
5411 : diag::warn_init_list_constant_narrowing)
5412 << InitE->getSourceRange()
5413 << ConstantValue
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005414 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005415 } else
5416 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005417 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005418 ? diag::err_init_list_variable_narrowing
5419 : diag::warn_init_list_variable_narrowing)
5420 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005421 << InitE->getType().getLocalUnqualifiedType()
5422 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005423
5424 llvm::SmallString<128> StaticCast;
5425 llvm::raw_svector_ostream OS(StaticCast);
5426 OS << "static_cast<";
5427 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5428 // It's important to use the typedef's name if there is one so that the
5429 // fixit doesn't break code using types like int64_t.
5430 //
5431 // FIXME: This will break if the typedef requires qualification. But
5432 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005433 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005434 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5435 OS << BT->getName(S.getLangOptions());
5436 else {
5437 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5438 // with a broken cast.
5439 return;
5440 }
5441 OS << ">(";
5442 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5443 << InitE->getSourceRange()
5444 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5445 << FixItHint::CreateInsertion(
5446 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5447}
5448
Douglas Gregore1314a62009-12-18 05:02:21 +00005449//===----------------------------------------------------------------------===//
5450// Initialization helper functions
5451//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005452bool
5453Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5454 ExprResult Init) {
5455 if (Init.isInvalid())
5456 return false;
5457
5458 Expr *InitE = Init.get();
5459 assert(InitE && "No initialization expression");
5460
5461 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5462 SourceLocation());
5463 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005464 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005465}
5466
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005467ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005468Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5469 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005470 ExprResult Init,
5471 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005472 if (Init.isInvalid())
5473 return ExprError();
5474
John McCall1f425642010-11-11 03:21:53 +00005475 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005476 assert(InitE && "No initialization expression?");
5477
5478 if (EqualLoc.isInvalid())
5479 EqualLoc = InitE->getLocStart();
5480
5481 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5482 EqualLoc);
5483 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5484 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005485
5486 bool Constant = false;
5487 APValue Result;
5488 if (TopLevelOfInitList &&
5489 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5490 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5491 Constant, Result);
5492 }
John McCallfaf5fb42010-08-26 23:41:50 +00005493 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005494}