blob: a4282e294626fb776a0e26f3b5a359bdbec213a7 [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
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000173 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000198 void CheckComplexType(const InitializedEntity &Entity,
199 InitListExpr *IList, QualType DeclType,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000203 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000204 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000208 void CheckReferenceType(const InitializedEntity &Entity,
209 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000210 unsigned &Index,
211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000213 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000214 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000217 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000218 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000219 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000222 unsigned &StructuredIndex,
223 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000224 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000225 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000226 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000230 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000231 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000232 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000233 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 RecordDecl::field_iterator *NextField,
235 llvm::APSInt *NextElementIndex,
236 unsigned &Index,
237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000239 bool FinishSubobjectInit,
240 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
242 QualType CurrentObjectType,
243 InitListExpr *StructuredList,
244 unsigned StructuredIndex,
245 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000246 void UpdateStructuredListElement(InitListExpr *StructuredList,
247 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248 Expr *expr);
249 int numArrayElements(QualType DeclType);
250 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000251
Douglas Gregor2bb07652009-12-22 00:05:34 +0000252 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000255 void FillInValueInitializations(const InitializedEntity &Entity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000257 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
258 Expr *InitExpr, FieldDecl *Field,
259 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000260 void CheckValueInitializable(const InitializedEntity &Entity);
261
Douglas Gregor85df8d82009-01-29 00:45:39 +0000262public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000263 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000264 InitListExpr *IL, QualType &T, bool VerifyOnly,
265 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000266 bool HadError() { return hadError; }
267
268 // @brief Retrieves the fully-structured initializer list used for
269 // semantic analysis and code generation.
270 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
271};
Chris Lattner9ececce2009-02-24 22:48:58 +0000272} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000273
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000274void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
275 assert(VerifyOnly &&
276 "CheckValueInitializable is only inteded for verification mode.");
277
278 SourceLocation Loc;
279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
282 if (InitSeq.Failed())
283 hadError = true;
284}
285
Douglas Gregor2bb07652009-12-22 00:05:34 +0000286void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
287 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000289 bool &RequiresSecondPass) {
290 SourceLocation Loc = ILE->getSourceRange().getBegin();
291 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000293 = InitializedEntity::InitializeMember(Field, &ParentEntity);
294 if (Init >= NumInits || !ILE->getInit(Init)) {
295 // FIXME: We probably don't need to handle references
296 // specially here, since value-initialization of references is
297 // handled in InitializationSequence.
298 if (Field->getType()->isReferenceType()) {
299 // C++ [dcl.init.aggr]p9:
300 // If an incomplete or empty initializer-list leaves a
301 // member of reference type uninitialized, the program is
302 // ill-formed.
303 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
304 << Field->getType()
305 << ILE->getSyntacticForm()->getSourceRange();
306 SemaRef.Diag(Field->getLocation(),
307 diag::note_uninit_reference_member);
308 hadError = true;
309 return;
310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
313 true);
314 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
315 if (!InitSeq) {
316 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
317 hadError = true;
318 return;
319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000320
John McCalldadc5752010-08-24 06:29:42 +0000321 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000322 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323 if (MemberInit.isInvalid()) {
324 hadError = true;
325 return;
326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (hadError) {
329 // Do nothing
330 } else if (Init < NumInits) {
331 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000332 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000333 // Value-initialization requires a constructor call, so
334 // extend the initializer list to include the constructor
335 // call and make a note that we'll need to take another pass
336 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000337 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000338 RequiresSecondPass = true;
339 }
340 } else if (InitListExpr *InnerILE
341 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000342 FillInValueInitializations(MemberEntity, InnerILE,
343 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000344}
345
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000346/// Recursively replaces NULL values within the given initializer list
347/// with expressions that perform value-initialization of the
348/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349void
Douglas Gregor723796a2009-12-16 06:35:08 +0000350InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
351 InitListExpr *ILE,
352 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000353 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000354 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000355 SourceLocation Loc = ILE->getSourceRange().getBegin();
356 if (ILE->getSyntacticForm())
357 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000358
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000359 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000360 if (RType->getDecl()->isUnion() &&
361 ILE->getInitializedFieldInUnion())
362 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
363 Entity, ILE, RequiresSecondPass);
364 else {
365 unsigned Init = 0;
366 for (RecordDecl::field_iterator
367 Field = RType->getDecl()->field_begin(),
368 FieldEnd = RType->getDecl()->field_end();
369 Field != FieldEnd; ++Field) {
370 if (Field->isUnnamedBitfield())
371 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000372
Douglas Gregor2bb07652009-12-22 00:05:34 +0000373 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000374 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375
376 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
377 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379
Douglas Gregor2bb07652009-12-22 00:05:34 +0000380 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 // Only look at the first initialization of a union.
383 if (RType->getDecl()->isUnion())
384 break;
385 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000386 }
387
388 return;
Mike Stump11289f42009-09-09 15:08:12 +0000389 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000390
391 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregor723796a2009-12-16 06:35:08 +0000393 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000394 unsigned NumInits = ILE->getNumInits();
395 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000396 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000397 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000398 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
399 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000402 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000403 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000404 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000406 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000407 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000408 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000409
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000411 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000412 if (hadError)
413 return;
414
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
416 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 ElementEntity.setElementIndex(Init);
418
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000419 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
420 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000421 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
422 true);
423 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
424 if (!InitSeq) {
425 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000426 hadError = true;
427 return;
428 }
429
John McCalldadc5752010-08-24 06:29:42 +0000430 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000431 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000432 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000433 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 return;
435 }
436
437 if (hadError) {
438 // Do nothing
439 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000440 // For arrays, just set the expression used for value-initialization
441 // of the "holes" in the array.
442 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
443 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
444 else
445 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000446 } else {
447 // For arrays, just set the expression used for value-initialization
448 // of the rest of elements and exit.
449 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
450 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
451 return;
452 }
453
Sebastian Redld201edf2011-06-05 13:59:11 +0000454 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000455 // Value-initialization requires a constructor call, so
456 // extend the initializer list to include the constructor
457 // call and make a note that we'll need to take another pass
458 // through the initializer list.
459 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
460 RequiresSecondPass = true;
461 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000462 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000463 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000464 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000465 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000466 }
467}
468
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000469
Douglas Gregor723796a2009-12-16 06:35:08 +0000470InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000471 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000472 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000473 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000474 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000475
Eli Friedman23a9e312008-05-19 19:16:24 +0000476 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000477 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000478 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000479 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000481 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000482 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000483
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000484 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000485 bool RequiresSecondPass = false;
486 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000487 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000489 RequiresSecondPass);
490 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000491}
492
493int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000494 // FIXME: use a proper constant
495 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000496 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000497 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000498 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
499 }
500 return maxElements;
501}
502
503int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000504 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000505 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000506 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000507 Field = structDecl->field_begin(),
508 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000510 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 ++InitializableMembers;
512 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000513 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000514 return std::min(InitializableMembers, 1);
515 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000516}
517
Anders Carlsson6cabf312010-01-23 23:23:01 +0000518void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000519 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000520 QualType T, unsigned &Index,
521 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000522 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000523 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 if (T->isArrayType())
526 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000527 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000528 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000529 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000530 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000531 else
David Blaikie83d382b2011-09-23 05:06:16 +0000532 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000533
Eli Friedmane0f832b2008-05-25 13:49:22 +0000534 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000535 if (!VerifyOnly)
536 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
537 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000538 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000539 hadError = true;
540 return;
541 }
542
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000543 // Build a structured initializer list corresponding to this subobject.
544 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000545 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
546 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000547 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
548 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000549 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000550
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000554 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000555 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000556 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000557
558 if (VerifyOnly) {
559 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
560 hadError = true;
561 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000562 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000563
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000564 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000565 // Update the structured sub-object initializer so that it's ending
566 // range corresponds with the end of the last initializer it used.
567 if (EndIndex < ParentIList->getNumInits()) {
568 SourceLocation EndLoc
569 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
570 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000573 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000574 if (T->isArrayType() || T->isRecordType()) {
575 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000576 AllowBraceElision ? diag::warn_missing_braces :
577 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000578 << StructuredSubobjectInitList->getSourceRange()
579 << FixItHint::CreateInsertion(
580 StructuredSubobjectInitList->getLocStart(), "{")
581 << FixItHint::CreateInsertion(
582 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000584 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000585 if (!AllowBraceElision)
586 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000587 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000588 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000589}
590
Anders Carlsson6cabf312010-01-23 23:23:01 +0000591void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000592 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000593 unsigned &Index,
594 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 unsigned &StructuredIndex,
596 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000597 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000598 if (!VerifyOnly) {
599 SyntacticToSemantic[IList] = StructuredList;
600 StructuredList->setSyntacticForm(IList);
601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000603 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000604 if (!VerifyOnly) {
605 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
606 IList->setType(ExprTy);
607 StructuredList->setType(ExprTy);
608 }
Eli Friedman85f54972008-05-25 13:22:35 +0000609 if (hadError)
610 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000611
Eli Friedman85f54972008-05-25 13:22:35 +0000612 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000614 if (VerifyOnly) {
615 if (SemaRef.getLangOptions().CPlusPlus ||
616 (SemaRef.getLangOptions().OpenCL &&
617 IList->getType()->isVectorType())) {
618 hadError = true;
619 }
620 return;
621 }
622
Eli Friedmanbd327452009-05-29 20:20:05 +0000623 if (StructuredIndex == 1 &&
624 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000625 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000626 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 hadError = true;
629 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000630 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000631 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000632 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000633 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000634 // Don't complain for incomplete types, since we'll get an error
635 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000636 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000637 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 CurrentObjectType->isArrayType()? 0 :
639 CurrentObjectType->isVectorType()? 1 :
640 CurrentObjectType->isScalarType()? 2 :
641 CurrentObjectType->isUnionType()? 3 :
642 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000643
644 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000645 if (SemaRef.getLangOptions().CPlusPlus) {
646 DK = diag::err_excess_initializers;
647 hadError = true;
648 }
Nate Begeman425038c2009-07-07 21:53:06 +0000649 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
650 DK = diag::err_excess_initializers;
651 hadError = true;
652 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000653
Chris Lattnerb0912a52009-02-24 22:50:46 +0000654 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000655 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000656 }
657 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000658
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000659 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
660 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000661 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000662 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000663 << FixItHint::CreateRemoval(IList->getLocStart())
664 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000665}
666
Anders Carlsson6cabf312010-01-23 23:23:01 +0000667void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000668 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000669 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000670 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671 unsigned &Index,
672 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000673 unsigned &StructuredIndex,
674 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000675 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
676 // Explicitly braced initializer for complex type can be real+imaginary
677 // parts.
678 CheckComplexType(Entity, IList, DeclType, Index,
679 StructuredList, StructuredIndex);
680 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000681 CheckScalarType(Entity, IList, DeclType, Index,
682 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000683 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000685 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000686 } else if (DeclType->isAggregateType()) {
687 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000688 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000689 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000690 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000691 StructuredList, StructuredIndex,
692 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000693 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000694 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000695 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000698 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000699 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000700 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000701 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000702 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
703 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000704 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000705 if (!VerifyOnly)
706 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
707 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000708 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 } else if (DeclType->isRecordType()) {
710 // C++ [dcl.init]p14:
711 // [...] If the class is an aggregate (8.5.1), and the initializer
712 // is a brace-enclosed list, see 8.5.1.
713 //
714 // Note: 8.5.1 is handled below; here, we diagnose the case where
715 // we have an initializer list and a destination type that is not
716 // an aggregate.
717 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000718 if (!VerifyOnly)
719 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
720 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000721 hadError = true;
722 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000723 CheckReferenceType(Entity, IList, DeclType, Index,
724 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000725 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000726 if (!VerifyOnly)
727 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
728 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000729 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000730 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 if (!VerifyOnly)
732 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
733 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000734 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000735 }
736}
737
Anders Carlsson6cabf312010-01-23 23:23:01 +0000738void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000739 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000740 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 unsigned &Index,
742 InitListExpr *StructuredList,
743 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000744 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000745 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
746 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000747 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000748 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 = getStructuredSubobjectInit(IList, Index, ElemType,
750 StructuredList, StructuredIndex,
751 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000752 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000753 newStructuredList, newStructuredIndex);
754 ++StructuredIndex;
755 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000756 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000757 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000758 return CheckScalarType(Entity, IList, ElemType, Index,
759 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000760 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000761 return CheckReferenceType(Entity, IList, ElemType, Index,
762 StructuredList, StructuredIndex);
763 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000764
John McCall5decec92011-02-21 07:57:55 +0000765 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
766 // arrayType can be incomplete if we're initializing a flexible
767 // array member. There's nothing we can do with the completed
768 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769
John McCall5decec92011-02-21 07:57:55 +0000770 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000771 if (!VerifyOnly) {
772 CheckStringInit(Str, ElemType, arrayType, SemaRef);
773 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
774 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000775 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000776 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 }
John McCall5decec92011-02-21 07:57:55 +0000778
779 // Fall through for subaggregate initialization.
780
781 } else if (SemaRef.getLangOptions().CPlusPlus) {
782 // C++ [dcl.init.aggr]p12:
783 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000784 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000785 // an initializer-list. If the initializer can initialize a
786 // member, the member is initialized. [...]
787
788 // FIXME: Better EqualLoc?
789 InitializationKind Kind =
790 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
791 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
792
793 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000794 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000795 ExprResult Result =
796 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
797 if (Result.isInvalid())
798 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000799
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000800 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000801 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 }
John McCall5decec92011-02-21 07:57:55 +0000803 ++Index;
804 return;
805 }
806
807 // Fall through for subaggregate initialization
808 } else {
809 // C99 6.7.8p13:
810 //
811 // The initializer for a structure or union object that has
812 // automatic storage duration shall be either an initializer
813 // list as described below, or a single expression that has
814 // compatible structure or union type. In the latter case, the
815 // initial value of the object, including unnamed members, is
816 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000817 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000818 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000819 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
820 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000821 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000822 if (ExprRes.isInvalid())
823 hadError = true;
824 else {
825 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
826 if (ExprRes.isInvalid())
827 hadError = true;
828 }
829 UpdateStructuredListElement(StructuredList, StructuredIndex,
830 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000831 ++Index;
832 return;
833 }
John Wiegley01296292011-04-08 18:41:53 +0000834 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000835 // Fall through for subaggregate initialization
836 }
837
838 // C++ [dcl.init.aggr]p12:
839 //
840 // [...] Otherwise, if the member is itself a non-empty
841 // subaggregate, brace elision is assumed and the initializer is
842 // considered for the initialization of the first member of
843 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000844 if (!SemaRef.getLangOptions().OpenCL &&
845 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000846 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
847 StructuredIndex);
848 ++StructuredIndex;
849 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000850 if (!VerifyOnly) {
851 // We cannot initialize this element, so let
852 // PerformCopyInitialization produce the appropriate diagnostic.
853 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
854 SemaRef.Owned(expr),
855 /*TopLevelOfInitList=*/true);
856 }
John McCall5decec92011-02-21 07:57:55 +0000857 hadError = true;
858 ++Index;
859 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000860 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000861}
862
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000863void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
864 InitListExpr *IList, QualType DeclType,
865 unsigned &Index,
866 InitListExpr *StructuredList,
867 unsigned &StructuredIndex) {
868 assert(Index == 0 && "Index in explicit init list must be zero");
869
870 // As an extension, clang supports complex initializers, which initialize
871 // a complex number component-wise. When an explicit initializer list for
872 // a complex number contains two two initializers, this extension kicks in:
873 // it exepcts the initializer list to contain two elements convertible to
874 // the element type of the complex type. The first element initializes
875 // the real part, and the second element intitializes the imaginary part.
876
877 if (IList->getNumInits() != 2)
878 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
879 StructuredIndex);
880
881 // This is an extension in C. (The builtin _Complex type does not exist
882 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000883 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000884 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
885 << IList->getSourceRange();
886
887 // Initialize the complex number.
888 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
889 InitializedEntity ElementEntity =
890 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
891
892 for (unsigned i = 0; i < 2; ++i) {
893 ElementEntity.setElementIndex(Index);
894 CheckSubElementType(ElementEntity, IList, elementType, Index,
895 StructuredList, StructuredIndex);
896 }
897}
898
899
Anders Carlsson6cabf312010-01-23 23:23:01 +0000900void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000901 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000902 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 InitListExpr *StructuredList,
904 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000905 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000906 if (!VerifyOnly)
907 SemaRef.Diag(IList->getLocStart(),
908 SemaRef.getLangOptions().CPlusPlus0x ?
909 diag::warn_cxx98_compat_empty_scalar_initializer :
910 diag::err_empty_scalar_initializer)
911 << IList->getSourceRange();
912 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000913 ++Index;
914 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000915 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000916 }
John McCall643169b2010-11-11 00:46:36 +0000917
918 Expr *expr = IList->getInit(Index);
919 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000920 if (!VerifyOnly)
921 SemaRef.Diag(SubIList->getLocStart(),
922 diag::warn_many_braces_around_scalar_init)
923 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000924
925 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
926 StructuredIndex);
927 return;
928 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000929 if (!VerifyOnly)
930 SemaRef.Diag(expr->getSourceRange().getBegin(),
931 diag::err_designator_for_scalar_init)
932 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000933 hadError = true;
934 ++Index;
935 ++StructuredIndex;
936 return;
937 }
938
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000939 if (VerifyOnly) {
940 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
941 hadError = true;
942 ++Index;
943 return;
944 }
945
John McCall643169b2010-11-11 00:46:36 +0000946 ExprResult Result =
947 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000948 SemaRef.Owned(expr),
949 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000950
951 Expr *ResultExpr = 0;
952
953 if (Result.isInvalid())
954 hadError = true; // types weren't compatible.
955 else {
956 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000957
John McCall643169b2010-11-11 00:46:36 +0000958 if (ResultExpr != expr) {
959 // The type was promoted, update initializer list.
960 IList->setInit(Index, ResultExpr);
961 }
962 }
963 if (hadError)
964 ++StructuredIndex;
965 else
966 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
967 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000968}
969
Anders Carlsson6cabf312010-01-23 23:23:01 +0000970void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
971 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000972 unsigned &Index,
973 InitListExpr *StructuredList,
974 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000975 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000976 // FIXME: It would be wonderful if we could point at the actual member. In
977 // general, it would be useful to pass location information down the stack,
978 // so that we know the location (or decl) of the "current object" being
979 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000980 if (!VerifyOnly)
981 SemaRef.Diag(IList->getLocStart(),
982 diag::err_init_reference_member_uninitialized)
983 << DeclType
984 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000985 hadError = true;
986 ++Index;
987 ++StructuredIndex;
988 return;
989 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000990
991 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000992 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000993 if (!VerifyOnly)
994 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
995 << DeclType << IList->getSourceRange();
996 hadError = true;
997 ++Index;
998 ++StructuredIndex;
999 return;
1000 }
1001
1002 if (VerifyOnly) {
1003 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1004 hadError = true;
1005 ++Index;
1006 return;
1007 }
1008
1009 ExprResult Result =
1010 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1011 SemaRef.Owned(expr),
1012 /*TopLevelOfInitList=*/true);
1013
1014 if (Result.isInvalid())
1015 hadError = true;
1016
1017 expr = Result.takeAs<Expr>();
1018 IList->setInit(Index, expr);
1019
1020 if (hadError)
1021 ++StructuredIndex;
1022 else
1023 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1024 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001025}
1026
Anders Carlsson6cabf312010-01-23 23:23:01 +00001027void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001028 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001029 unsigned &Index,
1030 InitListExpr *StructuredList,
1031 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001032 const VectorType *VT = DeclType->getAs<VectorType>();
1033 unsigned maxElements = VT->getNumElements();
1034 unsigned numEltsInit = 0;
1035 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001036
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001037 if (Index >= IList->getNumInits()) {
1038 // Make sure the element type can be value-initialized.
1039 if (VerifyOnly)
1040 CheckValueInitializable(
1041 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1042 return;
1043 }
1044
John McCall6a16b2f2010-10-30 00:11:39 +00001045 if (!SemaRef.getLangOptions().OpenCL) {
1046 // If the initializing element is a vector, try to copy-initialize
1047 // instead of breaking it apart (which is doomed to failure anyway).
1048 Expr *Init = IList->getInit(Index);
1049 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001050 if (VerifyOnly) {
1051 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1052 hadError = true;
1053 ++Index;
1054 return;
1055 }
1056
John McCall6a16b2f2010-10-30 00:11:39 +00001057 ExprResult Result =
1058 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001059 SemaRef.Owned(Init),
1060 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001061
1062 Expr *ResultExpr = 0;
1063 if (Result.isInvalid())
1064 hadError = true; // types weren't compatible.
1065 else {
1066 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067
John McCall6a16b2f2010-10-30 00:11:39 +00001068 if (ResultExpr != Init) {
1069 // The type was promoted, update initializer list.
1070 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001071 }
1072 }
John McCall6a16b2f2010-10-30 00:11:39 +00001073 if (hadError)
1074 ++StructuredIndex;
1075 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001076 UpdateStructuredListElement(StructuredList, StructuredIndex,
1077 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001078 ++Index;
1079 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
John McCall6a16b2f2010-10-30 00:11:39 +00001082 InitializedEntity ElementEntity =
1083 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
John McCall6a16b2f2010-10-30 00:11:39 +00001085 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1086 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001087 if (Index >= IList->getNumInits()) {
1088 if (VerifyOnly)
1089 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001090 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001092
John McCall6a16b2f2010-10-30 00:11:39 +00001093 ElementEntity.setElementIndex(Index);
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
1096 }
1097 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001098 }
John McCall6a16b2f2010-10-30 00:11:39 +00001099
1100 InitializedEntity ElementEntity =
1101 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
John McCall6a16b2f2010-10-30 00:11:39 +00001103 // OpenCL initializers allows vectors to be constructed from vectors.
1104 for (unsigned i = 0; i < maxElements; ++i) {
1105 // Don't attempt to go past the end of the init list
1106 if (Index >= IList->getNumInits())
1107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
John McCall6a16b2f2010-10-30 00:11:39 +00001109 ElementEntity.setElementIndex(Index);
1110
1111 QualType IType = IList->getInit(Index)->getType();
1112 if (!IType->isVectorType()) {
1113 CheckSubElementType(ElementEntity, IList, elementType, Index,
1114 StructuredList, StructuredIndex);
1115 ++numEltsInit;
1116 } else {
1117 QualType VecType;
1118 const VectorType *IVT = IType->getAs<VectorType>();
1119 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
John McCall6a16b2f2010-10-30 00:11:39 +00001121 if (IType->isExtVectorType())
1122 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1123 else
1124 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001125 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001126 CheckSubElementType(ElementEntity, IList, VecType, Index,
1127 StructuredList, StructuredIndex);
1128 numEltsInit += numIElts;
1129 }
1130 }
1131
1132 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001133 if (numEltsInit != maxElements) {
1134 if (!VerifyOnly)
1135 SemaRef.Diag(IList->getSourceRange().getBegin(),
1136 diag::err_vector_incorrect_num_initializers)
1137 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1138 hadError = true;
1139 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001140}
1141
Anders Carlsson6cabf312010-01-23 23:23:01 +00001142void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001143 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001144 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001145 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001146 unsigned &Index,
1147 InitListExpr *StructuredList,
1148 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001149 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1150
Steve Narofff8ecff22008-05-01 22:18:59 +00001151 // Check for the special-case of initializing an array with a string.
1152 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001153 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001154 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001155 // We place the string literal directly into the resulting
1156 // initializer list. This is the only place where the structure
1157 // of the structured initializer list doesn't match exactly,
1158 // because doing so would involve allocating one character
1159 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001160 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001161 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1163 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1164 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001165 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001166 return;
1167 }
1168 }
John McCall66884dd2011-02-21 07:22:22 +00001169 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001170 // Check for VLAs; in standard C it would be possible to check this
1171 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1172 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001173 if (!VerifyOnly)
1174 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1175 diag::err_variable_object_no_init)
1176 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001177 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001178 ++Index;
1179 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001180 return;
1181 }
1182
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001183 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001184 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1185 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001186 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001187 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001189 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001190 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001191 maxElementsKnown = true;
1192 }
1193
John McCall66884dd2011-02-21 07:22:22 +00001194 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001195 while (Index < IList->getNumInits()) {
1196 Expr *Init = IList->getInit(Index);
1197 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001198 // If we're not the subobject that matches up with the '{' for
1199 // the designator, we shouldn't be handling the
1200 // designator. Return immediately.
1201 if (!SubobjectIsDesignatorContext)
1202 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001203
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001204 // Handle this designated initializer. elementIndex will be
1205 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001206 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001207 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001208 StructuredList, StructuredIndex, true,
1209 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001210 hadError = true;
1211 continue;
1212 }
1213
Douglas Gregor033d1252009-01-23 16:54:12 +00001214 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001215 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001218 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001219
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001220 // If the array is of incomplete type, keep track of the number of
1221 // elements in the initializer.
1222 if (!maxElementsKnown && elementIndex > maxElements)
1223 maxElements = elementIndex;
1224
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001225 continue;
1226 }
1227
1228 // If we know the maximum number of elements, and we've already
1229 // hit it, stop consuming elements in the initializer list.
1230 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001231 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001232
Anders Carlsson6cabf312010-01-23 23:23:01 +00001233 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 Entity);
1236 // Check this element.
1237 CheckSubElementType(ElementEntity, IList, elementType, Index,
1238 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001239 ++elementIndex;
1240
1241 // If the array is of incomplete type, keep track of the number of
1242 // elements in the initializer.
1243 if (!maxElementsKnown && elementIndex > maxElements)
1244 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001245 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001246 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001248 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001249 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001250 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001251 // Sizing an array implicitly to zero is not allowed by ISO C,
1252 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001253 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001254 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001255 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256
Mike Stump11289f42009-09-09 15:08:12 +00001257 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001259 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001260 if (!hadError && VerifyOnly) {
1261 // Check if there are any members of the array that get value-initialized.
1262 // If so, check if doing that is possible.
1263 // FIXME: This needs to detect holes left by designated initializers too.
1264 if (maxElementsKnown && elementIndex < maxElements)
1265 CheckValueInitializable(InitializedEntity::InitializeElement(
1266 SemaRef.Context, 0, Entity));
1267 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001268}
1269
Eli Friedman3fa64df2011-08-23 22:24:57 +00001270bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1271 Expr *InitExpr,
1272 FieldDecl *Field,
1273 bool TopLevelObject) {
1274 // Handle GNU flexible array initializers.
1275 unsigned FlexArrayDiag;
1276 if (isa<InitListExpr>(InitExpr) &&
1277 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1278 // Empty flexible array init always allowed as an extension
1279 FlexArrayDiag = diag::ext_flexible_array_init;
1280 } else if (SemaRef.getLangOptions().CPlusPlus) {
1281 // Disallow flexible array init in C++; it is not required for gcc
1282 // compatibility, and it needs work to IRGen correctly in general.
1283 FlexArrayDiag = diag::err_flexible_array_init;
1284 } else if (!TopLevelObject) {
1285 // Disallow flexible array init on non-top-level object
1286 FlexArrayDiag = diag::err_flexible_array_init;
1287 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1288 // Disallow flexible array init on anything which is not a variable.
1289 FlexArrayDiag = diag::err_flexible_array_init;
1290 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1291 // Disallow flexible array init on local variables.
1292 FlexArrayDiag = diag::err_flexible_array_init;
1293 } else {
1294 // Allow other cases.
1295 FlexArrayDiag = diag::ext_flexible_array_init;
1296 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001297
1298 if (!VerifyOnly) {
1299 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1300 FlexArrayDiag)
1301 << InitExpr->getSourceRange().getBegin();
1302 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1303 << Field;
1304 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001305
1306 return FlexArrayDiag != diag::ext_flexible_array_init;
1307}
1308
Anders Carlsson6cabf312010-01-23 23:23:01 +00001309void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001310 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001311 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001313 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001314 unsigned &Index,
1315 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001316 unsigned &StructuredIndex,
1317 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001318 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001319
Eli Friedman23a9e312008-05-19 19:16:24 +00001320 // If the record is invalid, some of it's members are invalid. To avoid
1321 // confusion, we forgo checking the intializer for the entire record.
1322 if (structDecl->isInvalidDecl()) {
1323 hadError = true;
1324 return;
Mike Stump11289f42009-09-09 15:08:12 +00001325 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001326
1327 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001328 // Value-initialize the first named member of the union.
1329 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1330 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1331 Field != FieldEnd; ++Field) {
1332 if (Field->getDeclName()) {
1333 if (VerifyOnly)
1334 CheckValueInitializable(
1335 InitializedEntity::InitializeMember(*Field, &Entity));
1336 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001337 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001338 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001339 }
1340 }
1341 return;
1342 }
1343
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001344 // If structDecl is a forward declaration, this loop won't do
1345 // anything except look at designated initializers; That's okay,
1346 // because an error should get printed out elsewhere. It might be
1347 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001348 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001349 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001350 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001351 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001352 while (Index < IList->getNumInits()) {
1353 Expr *Init = IList->getInit(Index);
1354
1355 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001356 // If we're not the subobject that matches up with the '{' for
1357 // the designator, we shouldn't be handling the
1358 // designator. Return immediately.
1359 if (!SubobjectIsDesignatorContext)
1360 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001361
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001362 // Handle this designated initializer. Field will be updated to
1363 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001364 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001366 StructuredList, StructuredIndex,
1367 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001368 hadError = true;
1369
Douglas Gregora9add4e2009-02-12 19:00:39 +00001370 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001371
1372 // Disable check for missing fields when designators are used.
1373 // This matches gcc behaviour.
1374 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001375 continue;
1376 }
1377
1378 if (Field == FieldEnd) {
1379 // We've run out of fields. We're done.
1380 break;
1381 }
1382
Douglas Gregora9add4e2009-02-12 19:00:39 +00001383 // We've already initialized a member of a union. We're done.
1384 if (InitializedSomething && DeclType->isUnionType())
1385 break;
1386
Douglas Gregor91f84212008-12-11 16:49:14 +00001387 // If we've hit the flexible array member at the end, we're done.
1388 if (Field->getType()->isIncompleteArrayType())
1389 break;
1390
Douglas Gregor51695702009-01-29 16:53:55 +00001391 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001392 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001393 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001394 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001395 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001396
Douglas Gregora82064c2011-06-29 21:51:31 +00001397 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001398 bool InvalidUse;
1399 if (VerifyOnly)
1400 InvalidUse = !SemaRef.CanUseDecl(*Field);
1401 else
1402 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1403 IList->getInit(Index)->getLocStart());
1404 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001405 ++Index;
1406 ++Field;
1407 hadError = true;
1408 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001409 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001410
Anders Carlsson6cabf312010-01-23 23:23:01 +00001411 InitializedEntity MemberEntity =
1412 InitializedEntity::InitializeMember(*Field, &Entity);
1413 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1414 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001415 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001416
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001417 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001418 // Initialize the first field within the union.
1419 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001420 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001421
1422 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001423 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001424
John McCalle40b58e2010-03-11 19:32:38 +00001425 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001426 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1427 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1428 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001429 // It is possible we have one or more unnamed bitfields remaining.
1430 // Find first (if any) named field and emit warning.
1431 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1432 it != end; ++it) {
1433 if (!it->isUnnamedBitfield()) {
1434 SemaRef.Diag(IList->getSourceRange().getEnd(),
1435 diag::warn_missing_field_initializers) << it->getName();
1436 break;
1437 }
1438 }
1439 }
1440
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001441 // Check that any remaining fields can be value-initialized.
1442 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1443 !Field->getType()->isIncompleteArrayType()) {
1444 // FIXME: Should check for holes left by designated initializers too.
1445 for (; Field != FieldEnd && !hadError; ++Field) {
1446 if (!Field->isUnnamedBitfield())
1447 CheckValueInitializable(
1448 InitializedEntity::InitializeMember(*Field, &Entity));
1449 }
1450 }
1451
Mike Stump11289f42009-09-09 15:08:12 +00001452 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001453 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001454 return;
1455
Eli Friedman3fa64df2011-08-23 22:24:57 +00001456 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1457 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001458 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001459 ++Index;
1460 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001461 }
1462
Anders Carlsson6cabf312010-01-23 23:23:01 +00001463 InitializedEntity MemberEntity =
1464 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465
Anders Carlsson6cabf312010-01-23 23:23:01 +00001466 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 StructuredList, StructuredIndex);
1469 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001471 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001472}
Steve Narofff8ecff22008-05-01 22:18:59 +00001473
Douglas Gregord5846a12009-04-15 06:41:24 +00001474/// \brief Expand a field designator that refers to a member of an
1475/// anonymous struct or union into a series of field designators that
1476/// refers to the field within the appropriate subobject.
1477///
Douglas Gregord5846a12009-04-15 06:41:24 +00001478static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001479 DesignatedInitExpr *DIE,
1480 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001481 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001482 typedef DesignatedInitExpr::Designator Designator;
1483
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001486 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1487 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1488 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001489 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001490 DIE->getDesignator(DesigIdx)->getDotLoc(),
1491 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1492 else
1493 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1494 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001495 assert(isa<FieldDecl>(*PI));
1496 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001497 }
1498
1499 // Expand the current designator into the set of replacement
1500 // designators, so we have a full subobject path down to where the
1501 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001502 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001503 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001504}
Mike Stump11289f42009-09-09 15:08:12 +00001505
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001507/// corresponds to FieldName.
1508static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1509 IdentifierInfo *FieldName) {
1510 assert(AnonField->isAnonymousStructOrUnion());
1511 Decl *NextDecl = AnonField->getNextDeclInContext();
1512 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1513 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1514 return IF;
1515 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001516 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001517 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001518}
1519
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001520static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1521 DesignatedInitExpr *DIE) {
1522 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1523 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1524 for (unsigned I = 0; I < NumIndexExprs; ++I)
1525 IndexExprs[I] = DIE->getSubExpr(I + 1);
1526 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1527 DIE->size(), IndexExprs.data(),
1528 NumIndexExprs, DIE->getEqualOrColonLoc(),
1529 DIE->usesGNUSyntax(), DIE->getInit());
1530}
1531
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001532namespace {
1533
1534// Callback to only accept typo corrections that are for field members of
1535// the given struct or union.
1536class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1537 public:
1538 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1539 : Record(RD) {}
1540
1541 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1542 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1543 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1544 }
1545
1546 private:
1547 RecordDecl *Record;
1548};
1549
1550}
1551
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001552/// @brief Check the well-formedness of a C99 designated initializer.
1553///
1554/// Determines whether the designated initializer @p DIE, which
1555/// resides at the given @p Index within the initializer list @p
1556/// IList, is well-formed for a current object of type @p DeclType
1557/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001558/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001559/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001560///
1561/// @param IList The initializer list in which this designated
1562/// initializer occurs.
1563///
Douglas Gregora5324162009-04-15 04:56:10 +00001564/// @param DIE The designated initializer expression.
1565///
1566/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001567///
1568/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1569/// into which the designation in @p DIE should refer.
1570///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571/// @param NextField If non-NULL and the first designator in @p DIE is
1572/// a field, this will be set to the field declaration corresponding
1573/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001574///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575/// @param NextElementIndex If non-NULL and the first designator in @p
1576/// DIE is an array designator or GNU array-range designator, this
1577/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001578///
1579/// @param Index Index into @p IList where the designated initializer
1580/// @p DIE occurs.
1581///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001582/// @param StructuredList The initializer list expression that
1583/// describes all of the subobject initializers in the order they'll
1584/// actually be initialized.
1585///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001586/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001587bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001588InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001589 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001590 DesignatedInitExpr *DIE,
1591 unsigned DesigIdx,
1592 QualType &CurrentObjectType,
1593 RecordDecl::field_iterator *NextField,
1594 llvm::APSInt *NextElementIndex,
1595 unsigned &Index,
1596 InitListExpr *StructuredList,
1597 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001598 bool FinishSubobjectInit,
1599 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001600 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001601 // Check the actual initialization for the designated object type.
1602 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001603
1604 // Temporarily remove the designator expression from the
1605 // initializer list that the child calls see, so that we don't try
1606 // to re-process the designator.
1607 unsigned OldIndex = Index;
1608 IList->setInit(OldIndex, DIE->getInit());
1609
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001610 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001612
1613 // Restore the designated initializer expression in the syntactic
1614 // form of the initializer list.
1615 if (IList->getInit(OldIndex) != DIE->getInit())
1616 DIE->setInit(IList->getInit(OldIndex));
1617 IList->setInit(OldIndex, DIE);
1618
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001620 }
1621
Douglas Gregora5324162009-04-15 04:56:10 +00001622 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001623 bool IsFirstDesignator = (DesigIdx == 0);
1624 if (!VerifyOnly) {
1625 assert((IsFirstDesignator || StructuredList) &&
1626 "Need a non-designated initializer list to start from");
1627
1628 // Determine the structural initializer list that corresponds to the
1629 // current subobject.
1630 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1631 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1632 StructuredList, StructuredIndex,
1633 SourceRange(D->getStartLocation(),
1634 DIE->getSourceRange().getEnd()));
1635 assert(StructuredList && "Expected a structured initializer list");
1636 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001637
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001638 if (D->isFieldDesignator()) {
1639 // C99 6.7.8p7:
1640 //
1641 // If a designator has the form
1642 //
1643 // . identifier
1644 //
1645 // then the current object (defined below) shall have
1646 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001647 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001648 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001649 if (!RT) {
1650 SourceLocation Loc = D->getDotLoc();
1651 if (Loc.isInvalid())
1652 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001653 if (!VerifyOnly)
1654 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1655 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001656 ++Index;
1657 return true;
1658 }
1659
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001660 // Note: we perform a linear search of the fields here, despite
1661 // the fact that we have a faster lookup method, because we always
1662 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001663 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001665 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001666 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001667 Field = RT->getDecl()->field_begin(),
1668 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669 for (; Field != FieldEnd; ++Field) {
1670 if (Field->isUnnamedBitfield())
1671 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001673 // If we find a field representing an anonymous field, look in the
1674 // IndirectFieldDecl that follow for the designated initializer.
1675 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1676 if (IndirectFieldDecl *IF =
1677 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001678 // In verify mode, don't modify the original.
1679 if (VerifyOnly)
1680 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001681 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1682 D = DIE->getDesignator(DesigIdx);
1683 break;
1684 }
1685 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001686 if (KnownField && KnownField == *Field)
1687 break;
1688 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689 break;
1690
1691 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001692 }
1693
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001695 if (VerifyOnly) {
1696 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001697 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001698 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699
Douglas Gregord5846a12009-04-15 06:41:24 +00001700 // There was no normal field in the struct with the designated
1701 // name. Perform another lookup for this name, which may find
1702 // something that we can't designate (e.g., a member function),
1703 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001704 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001705 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001706 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001707 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 // Name lookup didn't find anything. Determine whether this
1709 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001710 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001711 TypoCorrection Corrected = SemaRef.CorrectTypo(
1712 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001713 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, &Validator,
1714 RT->getDecl());
1715 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001716 std::string CorrectedStr(
1717 Corrected.getAsString(SemaRef.getLangOptions()));
1718 std::string CorrectedQuotedStr(
1719 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001720 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001722 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001723 << FieldName << CurrentObjectType << CorrectedQuotedStr
1724 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001726 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001727 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001728 } else {
1729 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1730 << FieldName << CurrentObjectType;
1731 ++Index;
1732 return true;
1733 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001736 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001737 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001738 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001740 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001742 ++Index;
1743 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001744 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001745
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001746 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001747 // The replacement field comes from typo correction; find it
1748 // in the list of fields.
1749 FieldIndex = 0;
1750 Field = RT->getDecl()->field_begin();
1751 for (; Field != FieldEnd; ++Field) {
1752 if (Field->isUnnamedBitfield())
1753 continue;
1754
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001756 Field->getIdentifier() == ReplacementField->getIdentifier())
1757 break;
1758
1759 ++FieldIndex;
1760 }
1761 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001762 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001763
1764 // All of the fields of a union are located at the same place in
1765 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001766 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001767 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001768 if (!VerifyOnly)
1769 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001770 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001771
Douglas Gregora82064c2011-06-29 21:51:31 +00001772 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001773 bool InvalidUse;
1774 if (VerifyOnly)
1775 InvalidUse = !SemaRef.CanUseDecl(*Field);
1776 else
1777 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1778 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001779 ++Index;
1780 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001781 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001782
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 if (!VerifyOnly) {
1784 // Update the designator with the field declaration.
1785 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001786
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001787 // Make sure that our non-designated initializer list has space
1788 // for a subobject corresponding to this field.
1789 if (FieldIndex >= StructuredList->getNumInits())
1790 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1791 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001792
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001793 // This designator names a flexible array member.
1794 if (Field->getType()->isIncompleteArrayType()) {
1795 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001796 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001797 // We can't designate an object within the flexible array
1798 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001799 if (!VerifyOnly) {
1800 DesignatedInitExpr::Designator *NextD
1801 = DIE->getDesignator(DesigIdx + 1);
1802 SemaRef.Diag(NextD->getStartLocation(),
1803 diag::err_designator_into_flexible_array_member)
1804 << SourceRange(NextD->getStartLocation(),
1805 DIE->getSourceRange().getEnd());
1806 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1807 << *Field;
1808 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001809 Invalid = true;
1810 }
1811
Chris Lattner001b29c2010-10-10 17:49:49 +00001812 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1813 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001814 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001815 if (!VerifyOnly) {
1816 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1817 diag::err_flexible_array_init_needs_braces)
1818 << DIE->getInit()->getSourceRange();
1819 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1820 << *Field;
1821 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001822 Invalid = true;
1823 }
1824
Eli Friedman3fa64df2011-08-23 22:24:57 +00001825 // Check GNU flexible array initializer.
1826 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1827 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001828 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001829
1830 if (Invalid) {
1831 ++Index;
1832 return true;
1833 }
1834
1835 // Initialize the array.
1836 bool prevHadError = hadError;
1837 unsigned newStructuredIndex = FieldIndex;
1838 unsigned OldIndex = Index;
1839 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001840
1841 InitializedEntity MemberEntity =
1842 InitializedEntity::InitializeMember(*Field, &Entity);
1843 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001844 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001845
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 IList->setInit(OldIndex, DIE);
1847 if (hadError && !prevHadError) {
1848 ++Field;
1849 ++FieldIndex;
1850 if (NextField)
1851 *NextField = Field;
1852 StructuredIndex = FieldIndex;
1853 return true;
1854 }
1855 } else {
1856 // Recurse to check later designated subobjects.
1857 QualType FieldType = (*Field)->getType();
1858 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001860 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001861 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1863 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001864 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001865 true, false))
1866 return true;
1867 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001868
1869 // Find the position of the next field to be initialized in this
1870 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001871 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001872 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873
1874 // If this the first designator, our caller will continue checking
1875 // the rest of this struct/class/union subobject.
1876 if (IsFirstDesignator) {
1877 if (NextField)
1878 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001879 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001880 return false;
1881 }
1882
Douglas Gregor17bd0942009-01-28 23:36:17 +00001883 if (!FinishSubobjectInit)
1884 return false;
1885
Douglas Gregord5846a12009-04-15 06:41:24 +00001886 // We've already initialized something in the union; we're done.
1887 if (RT->getDecl()->isUnion())
1888 return hadError;
1889
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001890 // Check the remaining fields within this class/struct/union subobject.
1891 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Anders Carlsson6cabf312010-01-23 23:23:01 +00001893 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001894 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001895 return hadError && !prevHadError;
1896 }
1897
1898 // C99 6.7.8p6:
1899 //
1900 // If a designator has the form
1901 //
1902 // [ constant-expression ]
1903 //
1904 // then the current object (defined below) shall have array
1905 // type and the expression shall be an integer constant
1906 // expression. If the array is of unknown size, any
1907 // nonnegative value is valid.
1908 //
1909 // Additionally, cope with the GNU extension that permits
1910 // designators of the form
1911 //
1912 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001913 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001914 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001915 if (!VerifyOnly)
1916 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1917 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001918 ++Index;
1919 return true;
1920 }
1921
1922 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001923 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1924 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001925 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001926 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001927 DesignatedEndIndex = DesignatedStartIndex;
1928 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001929 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001930
Mike Stump11289f42009-09-09 15:08:12 +00001931 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001932 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001933 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001934 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001935 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001936
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001937 // Codegen can't handle evaluating array range designators that have side
1938 // effects, because we replicate the AST value for each initialized element.
1939 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1940 // elements with something that has a side effect, so codegen can emit an
1941 // "error unsupported" error instead of miscompiling the app.
1942 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001943 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001944 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001945 }
1946
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 if (isa<ConstantArrayType>(AT)) {
1948 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001949 DesignatedStartIndex
1950 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001951 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001952 DesignatedEndIndex
1953 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001954 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1955 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001956 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001957 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1958 diag::err_array_designator_too_large)
1959 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1960 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001961 ++Index;
1962 return true;
1963 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001964 } else {
1965 // Make sure the bit-widths and signedness match.
1966 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001967 DesignatedEndIndex
1968 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001969 else if (DesignatedStartIndex.getBitWidth() <
1970 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001971 DesignatedStartIndex
1972 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001973 DesignatedStartIndex.setIsUnsigned(true);
1974 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001977 // Make sure that our non-designated initializer list has space
1978 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001979 if (!VerifyOnly &&
1980 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001981 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001982 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001983
Douglas Gregor17bd0942009-01-28 23:36:17 +00001984 // Repeatedly perform subobject initializations in the range
1985 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001986
Douglas Gregor17bd0942009-01-28 23:36:17 +00001987 // Move to the next designator
1988 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1989 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001991 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001992 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001993
Douglas Gregor17bd0942009-01-28 23:36:17 +00001994 while (DesignatedStartIndex <= DesignatedEndIndex) {
1995 // Recurse to check later designated subobjects.
1996 QualType ElementType = AT->getElementType();
1997 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001999 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2001 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002002 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002003 (DesignatedStartIndex == DesignatedEndIndex),
2004 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002005 return true;
2006
2007 // Move to the next index in the array that we'll be initializing.
2008 ++DesignatedStartIndex;
2009 ElementIndex = DesignatedStartIndex.getZExtValue();
2010 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002011
2012 // If this the first designator, our caller will continue checking
2013 // the rest of this array subobject.
2014 if (IsFirstDesignator) {
2015 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002016 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002017 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002018 return false;
2019 }
Mike Stump11289f42009-09-09 15:08:12 +00002020
Douglas Gregor17bd0942009-01-28 23:36:17 +00002021 if (!FinishSubobjectInit)
2022 return false;
2023
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002024 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002025 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002027 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002028 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002029 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002030}
2031
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002032// Get the structured initializer list for a subobject of type
2033// @p CurrentObjectType.
2034InitListExpr *
2035InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2036 QualType CurrentObjectType,
2037 InitListExpr *StructuredList,
2038 unsigned StructuredIndex,
2039 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002040 if (VerifyOnly)
2041 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002042 Expr *ExistingInit = 0;
2043 if (!StructuredList)
2044 ExistingInit = SyntacticToSemantic[IList];
2045 else if (StructuredIndex < StructuredList->getNumInits())
2046 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002048 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2049 return Result;
2050
2051 if (ExistingInit) {
2052 // We are creating an initializer list that initializes the
2053 // subobjects of the current object, but there was already an
2054 // initialization that completely initialized the current
2055 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002056 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002057 // struct X { int a, b; };
2058 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002059 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002060 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2061 // designated initializer re-initializes the whole
2062 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002063 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002064 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002065 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002066 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002067 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002068 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002069 << ExistingInit->getSourceRange();
2070 }
2071
Mike Stump11289f42009-09-09 15:08:12 +00002072 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002073 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2074 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002075 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002076
Douglas Gregora8a089b2010-07-13 18:40:04 +00002077 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002078
Douglas Gregor6d00c992009-03-20 23:58:33 +00002079 // Pre-allocate storage for the structured initializer list.
2080 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002081 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002082 bool GotNumInits = false;
2083 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002084 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002085 GotNumInits = true;
2086 } else if (Index < IList->getNumInits()) {
2087 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002088 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002089 GotNumInits = true;
2090 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002091 }
2092
Mike Stump11289f42009-09-09 15:08:12 +00002093 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002094 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2095 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2096 NumElements = CAType->getSize().getZExtValue();
2097 // Simple heuristic so that we don't allocate a very large
2098 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002099 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002100 NumElements = 0;
2101 }
John McCall9dd450b2009-09-21 23:43:11 +00002102 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002103 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002104 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002105 RecordDecl *RDecl = RType->getDecl();
2106 if (RDecl->isUnion())
2107 NumElements = 1;
2108 else
Mike Stump11289f42009-09-09 15:08:12 +00002109 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002110 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002111 }
2112
Ted Kremenekac034612010-04-13 23:39:13 +00002113 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002114
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002115 // Link this new initializer list into the structured initializer
2116 // lists.
2117 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002118 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002119 else {
2120 Result->setSyntacticForm(IList);
2121 SyntacticToSemantic[IList] = Result;
2122 }
2123
2124 return Result;
2125}
2126
2127/// Update the initializer at index @p StructuredIndex within the
2128/// structured initializer list to the value @p expr.
2129void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2130 unsigned &StructuredIndex,
2131 Expr *expr) {
2132 // No structured initializer list to update
2133 if (!StructuredList)
2134 return;
2135
Ted Kremenekac034612010-04-13 23:39:13 +00002136 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2137 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002138 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002139 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 diag::warn_initializer_overrides)
2141 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002142 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002143 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002144 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145 << PrevInit->getSourceRange();
2146 }
Mike Stump11289f42009-09-09 15:08:12 +00002147
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002148 ++StructuredIndex;
2149}
2150
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002151/// Check that the given Index expression is a valid array designator
2152/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002153/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002154/// and produces a reasonable diagnostic if there is a
2155/// failure. Returns true if there was an error, false otherwise. If
2156/// everything went okay, Value will receive the value of the constant
2157/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002158static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002159CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002160 SourceLocation Loc = Index->getSourceRange().getBegin();
2161
2162 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002163 if (S.VerifyIntegerConstantExpression(Index, &Value))
2164 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002165
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002166 if (Value.isSigned() && Value.isNegative())
2167 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002168 << Value.toString(10) << Index->getSourceRange();
2169
Douglas Gregor51650d32009-01-23 21:04:18 +00002170 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 return false;
2172}
2173
John McCalldadc5752010-08-24 06:29:42 +00002174ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002175 SourceLocation Loc,
2176 bool GNUSyntax,
2177 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002178 typedef DesignatedInitExpr::Designator ASTDesignator;
2179
2180 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002181 SmallVector<ASTDesignator, 32> Designators;
2182 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002183
2184 // Build designators and check array designator expressions.
2185 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2186 const Designator &D = Desig.getDesignator(Idx);
2187 switch (D.getKind()) {
2188 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002189 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002190 D.getFieldLoc()));
2191 break;
2192
2193 case Designator::ArrayDesignator: {
2194 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2195 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002196 if (!Index->isTypeDependent() &&
2197 !Index->isValueDependent() &&
2198 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002199 Invalid = true;
2200 else {
2201 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002202 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002203 D.getRBracketLoc()));
2204 InitExpressions.push_back(Index);
2205 }
2206 break;
2207 }
2208
2209 case Designator::ArrayRangeDesignator: {
2210 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2211 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2212 llvm::APSInt StartValue;
2213 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002214 bool StartDependent = StartIndex->isTypeDependent() ||
2215 StartIndex->isValueDependent();
2216 bool EndDependent = EndIndex->isTypeDependent() ||
2217 EndIndex->isValueDependent();
2218 if ((!StartDependent &&
2219 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2220 (!EndDependent &&
2221 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002222 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002223 else {
2224 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002225 if (StartDependent || EndDependent) {
2226 // Nothing to compute.
2227 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002228 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002229 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002230 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002231
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002232 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002233 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002234 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2236 Invalid = true;
2237 } else {
2238 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002239 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002240 D.getEllipsisLoc(),
2241 D.getRBracketLoc()));
2242 InitExpressions.push_back(StartIndex);
2243 InitExpressions.push_back(EndIndex);
2244 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002245 }
2246 break;
2247 }
2248 }
2249 }
2250
2251 if (Invalid || Init.isInvalid())
2252 return ExprError();
2253
2254 // Clear out the expressions within the designation.
2255 Desig.ClearExprs(*this);
2256
2257 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002258 = DesignatedInitExpr::Create(Context,
2259 Designators.data(), Designators.size(),
2260 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002261 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262
Richard Smithe4345902011-12-29 21:57:33 +00002263 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002264 Diag(DIE->getLocStart(), diag::ext_designated_init)
2265 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002266
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002267 return Owned(DIE);
2268}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002269
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002270//===----------------------------------------------------------------------===//
2271// Initialization entity
2272//===----------------------------------------------------------------------===//
2273
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002275 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002276 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002277{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002278 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2279 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002280 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002281 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002282 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002283 Type = VT->getElementType();
2284 } else {
2285 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2286 assert(CT && "Unexpected type");
2287 Kind = EK_ComplexElement;
2288 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002289 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002290}
2291
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002292InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002293 CXXBaseSpecifier *Base,
2294 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002295{
2296 InitializedEntity Result;
2297 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002298 Result.Base = reinterpret_cast<uintptr_t>(Base);
2299 if (IsInheritedVirtualBase)
2300 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301
Douglas Gregor1b303932009-12-22 15:35:07 +00002302 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002303 return Result;
2304}
2305
Douglas Gregor85dabae2009-12-16 01:38:02 +00002306DeclarationName InitializedEntity::getName() const {
2307 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002308 case EK_Parameter: {
2309 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2310 return (D ? D->getDeclName() : DeclarationName());
2311 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002312
2313 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002314 case EK_Member:
2315 return VariableOrMember->getDeclName();
2316
2317 case EK_Result:
2318 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002319 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002320 case EK_Temporary:
2321 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002322 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002323 case EK_ArrayElement:
2324 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002325 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002326 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002327 return DeclarationName();
2328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329
Douglas Gregor85dabae2009-12-16 01:38:02 +00002330 // Silence GCC warning
2331 return DeclarationName();
2332}
2333
Douglas Gregora4b592a2009-12-19 03:01:41 +00002334DeclaratorDecl *InitializedEntity::getDecl() const {
2335 switch (getKind()) {
2336 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002337 case EK_Member:
2338 return VariableOrMember;
2339
John McCall31168b02011-06-15 23:02:42 +00002340 case EK_Parameter:
2341 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2342
Douglas Gregora4b592a2009-12-19 03:01:41 +00002343 case EK_Result:
2344 case EK_Exception:
2345 case EK_New:
2346 case EK_Temporary:
2347 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002348 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002349 case EK_ArrayElement:
2350 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002351 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002352 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002353 return 0;
2354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002355
Douglas Gregora4b592a2009-12-19 03:01:41 +00002356 // Silence GCC warning
2357 return 0;
2358}
2359
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002360bool InitializedEntity::allowsNRVO() const {
2361 switch (getKind()) {
2362 case EK_Result:
2363 case EK_Exception:
2364 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002366 case EK_Variable:
2367 case EK_Parameter:
2368 case EK_Member:
2369 case EK_New:
2370 case EK_Temporary:
2371 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002372 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002373 case EK_ArrayElement:
2374 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002375 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002376 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002377 break;
2378 }
2379
2380 return false;
2381}
2382
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383//===----------------------------------------------------------------------===//
2384// Initialization sequence
2385//===----------------------------------------------------------------------===//
2386
2387void InitializationSequence::Step::Destroy() {
2388 switch (Kind) {
2389 case SK_ResolveAddressOfOverloadedFunction:
2390 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002391 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002392 case SK_CastDerivedToBaseLValue:
2393 case SK_BindReference:
2394 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002395 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 case SK_UserConversion:
2397 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002398 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002400 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002401 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002402 case SK_UnwrapInitList:
2403 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002404 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002405 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002406 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002407 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002408 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002409 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002410 case SK_PassByIndirectCopyRestore:
2411 case SK_PassByIndirectRestore:
2412 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002413 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002414
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002415 case SK_ConversionSequence:
2416 delete ICS;
2417 }
2418}
2419
Douglas Gregor838fcc32010-03-26 20:14:36 +00002420bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002421 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002422}
2423
2424bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002425 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002426 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427
Douglas Gregor838fcc32010-03-26 20:14:36 +00002428 switch (getFailureKind()) {
2429 case FK_TooManyInitsForReference:
2430 case FK_ArrayNeedsInitList:
2431 case FK_ArrayNeedsInitListOrStringLiteral:
2432 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2433 case FK_NonConstLValueReferenceBindingToTemporary:
2434 case FK_NonConstLValueReferenceBindingToUnrelated:
2435 case FK_RValueReferenceBindingToLValue:
2436 case FK_ReferenceInitDropsQualifiers:
2437 case FK_ReferenceInitFailed:
2438 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002439 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002440 case FK_TooManyInitsForScalar:
2441 case FK_ReferenceBindingToInitList:
2442 case FK_InitListBadDestinationType:
2443 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002444 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002445 case FK_ArrayTypeMismatch:
2446 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002447 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002448 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002449 case FK_PlaceholderType:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002450 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregor838fcc32010-03-26 20:14:36 +00002452 case FK_ReferenceInitOverloadFailed:
2453 case FK_UserConversionOverloadFailed:
2454 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002455 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002456 return FailedOverloadResult == OR_Ambiguous;
2457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458
Douglas Gregor838fcc32010-03-26 20:14:36 +00002459 return false;
2460}
2461
Douglas Gregorb33eed02010-04-16 22:09:46 +00002462bool InitializationSequence::isConstructorInitialization() const {
2463 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2464}
2465
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002466bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2467 const Expr *Initializer,
2468 bool *isInitializerConstant,
2469 APValue *ConstantValue) const {
2470 if (Steps.empty() || Initializer->isValueDependent())
2471 return false;
2472
2473 const Step &LastStep = Steps.back();
2474 if (LastStep.Kind != SK_ConversionSequence)
2475 return false;
2476
2477 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2478 const StandardConversionSequence *SCS = NULL;
2479 switch (ICS.getKind()) {
2480 case ImplicitConversionSequence::StandardConversion:
2481 SCS = &ICS.Standard;
2482 break;
2483 case ImplicitConversionSequence::UserDefinedConversion:
2484 SCS = &ICS.UserDefined.After;
2485 break;
2486 case ImplicitConversionSequence::AmbiguousConversion:
2487 case ImplicitConversionSequence::EllipsisConversion:
2488 case ImplicitConversionSequence::BadConversion:
2489 return false;
2490 }
2491
2492 // Check if SCS represents a narrowing conversion, according to C++0x
2493 // [dcl.init.list]p7:
2494 //
2495 // A narrowing conversion is an implicit conversion ...
2496 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2497 QualType FromType = SCS->getToType(0);
2498 QualType ToType = SCS->getToType(1);
2499 switch (PossibleNarrowing) {
2500 // * from a floating-point type to an integer type, or
2501 //
2502 // * from an integer type or unscoped enumeration type to a floating-point
2503 // type, except where the source is a constant expression and the actual
2504 // value after conversion will fit into the target type and will produce
2505 // the original value when converted back to the original type, or
2506 case ICK_Floating_Integral:
2507 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2508 *isInitializerConstant = false;
2509 return true;
2510 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2511 llvm::APSInt IntConstantValue;
2512 if (Initializer &&
2513 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2514 // Convert the integer to the floating type.
2515 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2516 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2517 llvm::APFloat::rmNearestTiesToEven);
2518 // And back.
2519 llvm::APSInt ConvertedValue = IntConstantValue;
2520 bool ignored;
2521 Result.convertToInteger(ConvertedValue,
2522 llvm::APFloat::rmTowardZero, &ignored);
2523 // If the resulting value is different, this was a narrowing conversion.
2524 if (IntConstantValue != ConvertedValue) {
2525 *isInitializerConstant = true;
2526 *ConstantValue = APValue(IntConstantValue);
2527 return true;
2528 }
2529 } else {
2530 // Variables are always narrowings.
2531 *isInitializerConstant = false;
2532 return true;
2533 }
2534 }
2535 return false;
2536
2537 // * from long double to double or float, or from double to float, except
2538 // where the source is a constant expression and the actual value after
2539 // conversion is within the range of values that can be represented (even
2540 // if it cannot be represented exactly), or
2541 case ICK_Floating_Conversion:
2542 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2543 // FromType is larger than ToType.
2544 Expr::EvalResult InitializerValue;
2545 // FIXME: Check whether Initializer is a constant expression according
2546 // to C++0x [expr.const], rather than just whether it can be folded.
Richard Smith7b553f12011-10-29 00:50:52 +00002547 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) &&
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002548 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2549 // Constant! (Except for FIXME above.)
2550 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2551 // Convert the source value into the target type.
2552 bool ignored;
2553 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2554 Ctx.getFloatTypeSemantics(ToType),
2555 llvm::APFloat::rmNearestTiesToEven, &ignored);
2556 // If there was no overflow, the source value is within the range of
2557 // values that can be represented.
2558 if (ConvertStatus & llvm::APFloat::opOverflow) {
2559 *isInitializerConstant = true;
2560 *ConstantValue = InitializerValue.Val;
2561 return true;
2562 }
2563 } else {
2564 *isInitializerConstant = false;
2565 return true;
2566 }
2567 }
2568 return false;
2569
2570 // * from an integer type or unscoped enumeration type to an integer type
2571 // that cannot represent all the values of the original type, except where
2572 // the source is a constant expression and the actual value after
2573 // conversion will fit into the target type and will produce the original
2574 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002575 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002576 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2577 // Boolean conversions can be from pointers and pointers to members
2578 // [conv.bool], and those aren't considered narrowing conversions.
2579 return false;
2580 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002581 case ICK_Integral_Conversion: {
2582 assert(FromType->isIntegralOrUnscopedEnumerationType());
2583 assert(ToType->isIntegralOrUnscopedEnumerationType());
2584 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2585 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2586 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2587 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2588
2589 if (FromWidth > ToWidth ||
2590 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2591 // Not all values of FromType can be represented in ToType.
2592 llvm::APSInt InitializerValue;
2593 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2594 *isInitializerConstant = true;
2595 *ConstantValue = APValue(InitializerValue);
2596
2597 // Add a bit to the InitializerValue so we don't have to worry about
2598 // signed vs. unsigned comparisons.
2599 InitializerValue = InitializerValue.extend(
2600 InitializerValue.getBitWidth() + 1);
2601 // Convert the initializer to and from the target width and signed-ness.
2602 llvm::APSInt ConvertedValue = InitializerValue;
2603 ConvertedValue = ConvertedValue.trunc(ToWidth);
2604 ConvertedValue.setIsSigned(ToSigned);
2605 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2606 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2607 // If the result is different, this was a narrowing conversion.
2608 return ConvertedValue != InitializerValue;
2609 } else {
2610 // Variables are always narrowings.
2611 *isInitializerConstant = false;
2612 return true;
2613 }
2614 }
2615 return false;
2616 }
2617
2618 default:
2619 // Other kinds of conversions are not narrowings.
2620 return false;
2621 }
2622}
2623
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002624void
2625InitializationSequence
2626::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2627 DeclAccessPair Found,
2628 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002629 Step S;
2630 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2631 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002632 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002633 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002634 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002635 Steps.push_back(S);
2636}
2637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002639 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002640 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002641 switch (VK) {
2642 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2643 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2644 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002645 default: llvm_unreachable("No such category");
2646 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002647 S.Type = BaseType;
2648 Steps.push_back(S);
2649}
2650
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002652 bool BindingTemporary) {
2653 Step S;
2654 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2655 S.Type = T;
2656 Steps.push_back(S);
2657}
2658
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002659void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2660 Step S;
2661 S.Kind = SK_ExtraneousCopyToTemporary;
2662 S.Type = T;
2663 Steps.push_back(S);
2664}
2665
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002666void
2667InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2668 DeclAccessPair FoundDecl,
2669 QualType T,
2670 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002671 Step S;
2672 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002673 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002674 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002675 S.Function.Function = Function;
2676 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677 Steps.push_back(S);
2678}
2679
2680void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002681 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002683 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002684 switch (VK) {
2685 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002686 S.Kind = SK_QualificationConversionRValue;
2687 break;
John McCall2536c6d2010-08-25 10:28:54 +00002688 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002689 S.Kind = SK_QualificationConversionXValue;
2690 break;
John McCall2536c6d2010-08-25 10:28:54 +00002691 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002692 S.Kind = SK_QualificationConversionLValue;
2693 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002694 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002695 S.Type = Ty;
2696 Steps.push_back(S);
2697}
2698
2699void InitializationSequence::AddConversionSequenceStep(
2700 const ImplicitConversionSequence &ICS,
2701 QualType T) {
2702 Step S;
2703 S.Kind = SK_ConversionSequence;
2704 S.Type = T;
2705 S.ICS = new ImplicitConversionSequence(ICS);
2706 Steps.push_back(S);
2707}
2708
Douglas Gregor51e77d52009-12-10 17:56:55 +00002709void InitializationSequence::AddListInitializationStep(QualType T) {
2710 Step S;
2711 S.Kind = SK_ListInitialization;
2712 S.Type = T;
2713 Steps.push_back(S);
2714}
2715
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002717InitializationSequence
2718::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2719 AccessSpecifier Access,
2720 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002721 bool HadMultipleCandidates,
2722 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002723 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002724 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002725 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002726 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002727 S.Function.Function = Constructor;
2728 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002729 Steps.push_back(S);
2730}
2731
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002732void InitializationSequence::AddZeroInitializationStep(QualType T) {
2733 Step S;
2734 S.Kind = SK_ZeroInitialization;
2735 S.Type = T;
2736 Steps.push_back(S);
2737}
2738
Douglas Gregore1314a62009-12-18 05:02:21 +00002739void InitializationSequence::AddCAssignmentStep(QualType T) {
2740 Step S;
2741 S.Kind = SK_CAssignment;
2742 S.Type = T;
2743 Steps.push_back(S);
2744}
2745
Eli Friedman78275202009-12-19 08:11:05 +00002746void InitializationSequence::AddStringInitStep(QualType T) {
2747 Step S;
2748 S.Kind = SK_StringInit;
2749 S.Type = T;
2750 Steps.push_back(S);
2751}
2752
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002753void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2754 Step S;
2755 S.Kind = SK_ObjCObjectConversion;
2756 S.Type = T;
2757 Steps.push_back(S);
2758}
2759
Douglas Gregore2f943b2011-02-22 18:29:51 +00002760void InitializationSequence::AddArrayInitStep(QualType T) {
2761 Step S;
2762 S.Kind = SK_ArrayInit;
2763 S.Type = T;
2764 Steps.push_back(S);
2765}
2766
John McCall31168b02011-06-15 23:02:42 +00002767void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2768 bool shouldCopy) {
2769 Step s;
2770 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2771 : SK_PassByIndirectRestore);
2772 s.Type = type;
2773 Steps.push_back(s);
2774}
2775
2776void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2777 Step S;
2778 S.Kind = SK_ProduceObjCObject;
2779 S.Type = T;
2780 Steps.push_back(S);
2781}
2782
Sebastian Redl29526f02011-11-27 16:50:07 +00002783void InitializationSequence::RewrapReferenceInitList(QualType T,
2784 InitListExpr *Syntactic) {
2785 assert(Syntactic->getNumInits() == 1 &&
2786 "Can only rewrap trivial init lists.");
2787 Step S;
2788 S.Kind = SK_UnwrapInitList;
2789 S.Type = Syntactic->getInit(0)->getType();
2790 Steps.insert(Steps.begin(), S);
2791
2792 S.Kind = SK_RewrapInitList;
2793 S.Type = T;
2794 S.WrappingSyntacticList = Syntactic;
2795 Steps.push_back(S);
2796}
2797
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002800 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002801 this->Failure = Failure;
2802 this->FailedOverloadResult = Result;
2803}
2804
2805//===----------------------------------------------------------------------===//
2806// Attempt initialization
2807//===----------------------------------------------------------------------===//
2808
John McCall31168b02011-06-15 23:02:42 +00002809static void MaybeProduceObjCObject(Sema &S,
2810 InitializationSequence &Sequence,
2811 const InitializedEntity &Entity) {
2812 if (!S.getLangOptions().ObjCAutoRefCount) return;
2813
2814 /// When initializing a parameter, produce the value if it's marked
2815 /// __attribute__((ns_consumed)).
2816 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2817 if (!Entity.isParameterConsumed())
2818 return;
2819
2820 assert(Entity.getType()->isObjCRetainableType() &&
2821 "consuming an object of unretainable type?");
2822 Sequence.AddProduceObjCObjectStep(Entity.getType());
2823
2824 /// When initializing a return value, if the return type is a
2825 /// retainable type, then returns need to immediately retain the
2826 /// object. If an autorelease is required, it will be done at the
2827 /// last instant.
2828 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2829 if (!Entity.getType()->isObjCRetainableType())
2830 return;
2831
2832 Sequence.AddProduceObjCObjectStep(Entity.getType());
2833 }
2834}
2835
Sebastian Redled2e5322011-12-22 14:44:04 +00002836/// \brief When initializing from init list via constructor, deal with the
2837/// empty init list and std::initializer_list special cases.
2838///
2839/// \return True if this was a special case, false otherwise.
2840static bool TryListConstructionSpecialCases(Sema &S,
2841 Expr **Args, unsigned NumArgs,
2842 CXXRecordDecl *DestRecordDecl,
2843 QualType DestType,
2844 InitializationSequence &Sequence) {
2845 // C++0x [dcl.init.list]p3:
2846 // List-initialization of an object of type T is defined as follows:
2847 // - If the initializer list has no elements and T is a class type with
2848 // a default constructor, the object is value-initialized.
2849 if (NumArgs == 0) {
2850 if (CXXConstructorDecl *DefaultConstructor =
2851 S.LookupDefaultConstructor(DestRecordDecl)) {
2852 if (DefaultConstructor->isDeleted() ||
2853 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2854 // Fake an overload resolution failure.
2855 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2856 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2857 DefaultConstructor->getAccess());
2858 if (FunctionTemplateDecl *ConstructorTmpl =
2859 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2860 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2861 /*ExplicitArgs*/ 0,
2862 Args, NumArgs, CandidateSet,
2863 /*SuppressUserConversions*/ false);
2864 else
2865 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2866 Args, NumArgs, CandidateSet,
2867 /*SuppressUserConversions*/ false);
2868 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002869 InitializationSequence::FK_ListConstructorOverloadFailed,
2870 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002871 } else
2872 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2873 DefaultConstructor->getAccess(),
2874 DestType,
2875 /*MultipleCandidates=*/false,
2876 /*FromInitList=*/true);
2877 return true;
2878 }
2879 }
2880
2881 // - Otherwise, if T is a specialization of std::initializer_list, [...]
2882 // FIXME: Implement.
2883
2884 // Not a special case.
2885 return false;
2886}
2887
2888/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2889/// enumerates the constructors of the initialized entity and performs overload
2890/// resolution to select the best.
2891/// If FromInitList is true, this is list-initialization of a non-aggregate
2892/// class type.
2893static void TryConstructorInitialization(Sema &S,
2894 const InitializedEntity &Entity,
2895 const InitializationKind &Kind,
2896 Expr **Args, unsigned NumArgs,
2897 QualType DestType,
2898 InitializationSequence &Sequence,
2899 bool FromInitList = false) {
2900 // Check constructor arguments for self reference.
2901 if (DeclaratorDecl *DD = Entity.getDecl())
2902 // Parameters arguments are occassionially constructed with itself,
2903 // for instance, in recursive functions. Skip them.
2904 if (!isa<ParmVarDecl>(DD))
2905 for (unsigned i = 0; i < NumArgs; ++i)
2906 S.CheckSelfReference(DD, Args[i]);
2907
2908 // Build the candidate set directly in the initialization sequence
2909 // structure, so that it will persist if we fail.
2910 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2911 CandidateSet.clear();
2912
2913 // Determine whether we are allowed to call explicit constructors or
2914 // explicit conversion operators.
2915 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2916 Kind.getKind() == InitializationKind::IK_Value ||
2917 Kind.getKind() == InitializationKind::IK_Default);
2918
2919 // The type we're constructing needs to be complete.
2920 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2921 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2922 }
2923
2924 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2925 assert(DestRecordType && "Constructor initialization requires record type");
2926 CXXRecordDecl *DestRecordDecl
2927 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2928
2929 if (FromInitList &&
2930 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2931 DestType, Sequence))
2932 return;
2933
2934 // - Otherwise, if T is a class type, constructors are considered. The
2935 // applicable constructors are enumerated, and the best one is chosen
2936 // through overload resolution.
2937 DeclContext::lookup_iterator Con, ConEnd;
2938 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2939 Con != ConEnd; ++Con) {
2940 NamedDecl *D = *Con;
2941 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2942 bool SuppressUserConversions = false;
2943
2944 // Find the constructor (which may be a template).
2945 CXXConstructorDecl *Constructor = 0;
2946 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2947 if (ConstructorTmpl)
2948 Constructor = cast<CXXConstructorDecl>(
2949 ConstructorTmpl->getTemplatedDecl());
2950 else {
2951 Constructor = cast<CXXConstructorDecl>(D);
2952
2953 // If we're performing copy initialization using a copy constructor, we
2954 // suppress user-defined conversions on the arguments.
2955 // FIXME: Move constructors?
2956 if (Kind.getKind() == InitializationKind::IK_Copy &&
2957 Constructor->isCopyConstructor())
2958 SuppressUserConversions = true;
2959 }
2960
2961 if (!Constructor->isInvalidDecl() &&
2962 (AllowExplicit || !Constructor->isExplicit())) {
2963 if (ConstructorTmpl)
2964 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2965 /*ExplicitArgs*/ 0,
2966 Args, NumArgs, CandidateSet,
2967 SuppressUserConversions);
2968 else
2969 S.AddOverloadCandidate(Constructor, FoundDecl,
2970 Args, NumArgs, CandidateSet,
2971 SuppressUserConversions);
2972 }
2973 }
2974
2975 SourceLocation DeclLoc = Kind.getLocation();
2976
2977 // Perform overload resolution. If it fails, return the failed result.
2978 OverloadCandidateSet::iterator Best;
2979 if (OverloadingResult Result
2980 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002981 Sequence.SetOverloadFailure(FromInitList ?
2982 InitializationSequence::FK_ListConstructorOverloadFailed :
2983 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002984 Result);
2985 return;
2986 }
2987
2988 // C++0x [dcl.init]p6:
2989 // If a program calls for the default initialization of an object
2990 // of a const-qualified type T, T shall be a class type with a
2991 // user-provided default constructor.
2992 if (Kind.getKind() == InitializationKind::IK_Default &&
2993 Entity.getType().isConstQualified() &&
2994 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2995 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2996 return;
2997 }
2998
2999 // Add the constructor initialization step. Any cv-qualification conversion is
3000 // subsumed by the initialization.
3001 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3002 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3003 Sequence.AddConstructorInitializationStep(CtorDecl,
3004 Best->FoundDecl.getAccess(),
3005 DestType, HadMultipleCandidates,
3006 FromInitList);
3007}
3008
Sebastian Redl29526f02011-11-27 16:50:07 +00003009static bool
3010ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3011 Expr *Initializer,
3012 QualType &SourceType,
3013 QualType &UnqualifiedSourceType,
3014 QualType UnqualifiedTargetType,
3015 InitializationSequence &Sequence) {
3016 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3017 S.Context.OverloadTy) {
3018 DeclAccessPair Found;
3019 bool HadMultipleCandidates = false;
3020 if (FunctionDecl *Fn
3021 = S.ResolveAddressOfOverloadedFunction(Initializer,
3022 UnqualifiedTargetType,
3023 false, Found,
3024 &HadMultipleCandidates)) {
3025 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3026 HadMultipleCandidates);
3027 SourceType = Fn->getType();
3028 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3029 } else if (!UnqualifiedTargetType->isRecordType()) {
3030 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3031 return true;
3032 }
3033 }
3034 return false;
3035}
3036
3037static void TryReferenceInitializationCore(Sema &S,
3038 const InitializedEntity &Entity,
3039 const InitializationKind &Kind,
3040 Expr *Initializer,
3041 QualType cv1T1, QualType T1,
3042 Qualifiers T1Quals,
3043 QualType cv2T2, QualType T2,
3044 Qualifiers T2Quals,
3045 InitializationSequence &Sequence);
3046
3047static void TryListInitialization(Sema &S,
3048 const InitializedEntity &Entity,
3049 const InitializationKind &Kind,
3050 InitListExpr *InitList,
3051 InitializationSequence &Sequence);
3052
3053/// \brief Attempt list initialization of a reference.
3054static void TryReferenceListInitialization(Sema &S,
3055 const InitializedEntity &Entity,
3056 const InitializationKind &Kind,
3057 InitListExpr *InitList,
3058 InitializationSequence &Sequence)
3059{
3060 // First, catch C++03 where this isn't possible.
3061 if (!S.getLangOptions().CPlusPlus0x) {
3062 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3063 return;
3064 }
3065
3066 QualType DestType = Entity.getType();
3067 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3068 Qualifiers T1Quals;
3069 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3070
3071 // Reference initialization via an initializer list works thus:
3072 // If the initializer list consists of a single element that is
3073 // reference-related to the referenced type, bind directly to that element
3074 // (possibly creating temporaries).
3075 // Otherwise, initialize a temporary with the initializer list and
3076 // bind to that.
3077 if (InitList->getNumInits() == 1) {
3078 Expr *Initializer = InitList->getInit(0);
3079 QualType cv2T2 = Initializer->getType();
3080 Qualifiers T2Quals;
3081 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3082
3083 // If this fails, creating a temporary wouldn't work either.
3084 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3085 T1, Sequence))
3086 return;
3087
3088 SourceLocation DeclLoc = Initializer->getLocStart();
3089 bool dummy1, dummy2, dummy3;
3090 Sema::ReferenceCompareResult RefRelationship
3091 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3092 dummy2, dummy3);
3093 if (RefRelationship >= Sema::Ref_Related) {
3094 // Try to bind the reference here.
3095 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3096 T1Quals, cv2T2, T2, T2Quals, Sequence);
3097 if (Sequence)
3098 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3099 return;
3100 }
3101 }
3102
3103 // Not reference-related. Create a temporary and bind to that.
3104 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3105
3106 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3107 if (Sequence) {
3108 if (DestType->isRValueReferenceType() ||
3109 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3110 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3111 else
3112 Sequence.SetFailed(
3113 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3114 }
3115}
3116
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003117/// \brief Attempt list initialization (C++0x [dcl.init.list])
3118static void TryListInitialization(Sema &S,
3119 const InitializedEntity &Entity,
3120 const InitializationKind &Kind,
3121 InitListExpr *InitList,
3122 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003123 QualType DestType = Entity.getType();
3124
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003125 // C++ doesn't allow scalar initialization with more than one argument.
3126 // But C99 complex numbers are scalars and it makes sense there.
3127 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3128 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3129 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3130 return;
3131 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003132 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003133 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003134 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003135 }
3136 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003137 if (S.getLangOptions().CPlusPlus0x)
3138 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3139 InitList->getNumInits(), DestType, Sequence,
3140 /*FromInitList=*/true);
3141 else
3142 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003143 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003144 }
3145
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003146 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003147 DestType, /*VerifyOnly=*/true,
3148 Kind.getKind() != InitializationKind::IK_Direct ||
3149 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003150 if (CheckInitList.HadError()) {
3151 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3152 return;
3153 }
3154
3155 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003156 Sequence.AddListInitializationStep(DestType);
3157}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158
3159/// \brief Try a reference initialization that involves calling a conversion
3160/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003161static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3162 const InitializedEntity &Entity,
3163 const InitializationKind &Kind,
3164 Expr *Initializer,
3165 bool AllowRValues,
3166 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003167 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003168 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3169 QualType T1 = cv1T1.getUnqualifiedType();
3170 QualType cv2T2 = Initializer->getType();
3171 QualType T2 = cv2T2.getUnqualifiedType();
3172
3173 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003174 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003175 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003176 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003177 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003178 ObjCConversion,
3179 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003180 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003181 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003182 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003183 (void)ObjCLifetimeConversion;
3184
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003185 // Build the candidate set directly in the initialization sequence
3186 // structure, so that it will persist if we fail.
3187 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3188 CandidateSet.clear();
3189
3190 // Determine whether we are allowed to call explicit constructors or
3191 // explicit conversion operators.
3192 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003194 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003195 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3196 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 // The type we're converting to is a class type. Enumerate its constructors
3198 // to see if there is a suitable conversion.
3199 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003202 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003203 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003204 NamedDecl *D = *Con;
3205 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3206
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003207 // Find the constructor (which may be a template).
3208 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003209 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003210 if (ConstructorTmpl)
3211 Constructor = cast<CXXConstructorDecl>(
3212 ConstructorTmpl->getTemplatedDecl());
3213 else
John McCalla0296f72010-03-19 07:35:19 +00003214 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216 if (!Constructor->isInvalidDecl() &&
3217 Constructor->isConvertingConstructor(AllowExplicit)) {
3218 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003219 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003220 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003221 &Initializer, 1, CandidateSet,
3222 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003223 else
John McCalla0296f72010-03-19 07:35:19 +00003224 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003225 &Initializer, 1, CandidateSet,
3226 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003228 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003229 }
John McCall3696dcb2010-08-17 07:23:57 +00003230 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3231 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232
Douglas Gregor496e8b342010-05-07 19:42:26 +00003233 const RecordType *T2RecordType = 0;
3234 if ((T2RecordType = T2->getAs<RecordType>()) &&
3235 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003236 // The type we're converting from is a class type, enumerate its conversion
3237 // functions.
3238 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3239
John McCallad371252010-01-20 00:46:10 +00003240 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003241 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003242 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3243 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003244 NamedDecl *D = *I;
3245 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3246 if (isa<UsingShadowDecl>(D))
3247 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003249 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3250 CXXConversionDecl *Conv;
3251 if (ConvTemplate)
3252 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3253 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003254 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003256 // If the conversion function doesn't return a reference type,
3257 // it can't be considered for this conversion unless we're allowed to
3258 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259 // FIXME: Do we need to make sure that we only consider conversion
3260 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003261 // break recursion.
3262 if ((AllowExplicit || !Conv->isExplicit()) &&
3263 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3264 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003265 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003266 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003267 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003268 else
John McCalla0296f72010-03-19 07:35:19 +00003269 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003270 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003271 }
3272 }
3273 }
John McCall3696dcb2010-08-17 07:23:57 +00003274 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3275 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003277 SourceLocation DeclLoc = Initializer->getLocStart();
3278
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003280 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003281 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003282 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003283 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003285 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003286
Chandler Carruth30141632011-02-25 19:41:05 +00003287 // This is the overload that will actually be used for the initialization, so
3288 // mark it as used.
3289 S.MarkDeclarationReferenced(DeclLoc, Function);
3290
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003291 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003292 if (isa<CXXConversionDecl>(Function))
3293 T2 = Function->getResultType();
3294 else
3295 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003296
3297 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003298 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003299 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003300 T2.getNonLValueExprType(S.Context),
3301 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003302
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003304 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003305 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003306 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003307 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003308 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003309 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003310
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003311 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003312 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003313 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003314 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003316 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003317 NewDerivedToBase, NewObjCConversion,
3318 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003319 if (NewRefRelationship == Sema::Ref_Incompatible) {
3320 // If the type we've converted to is not reference-related to the
3321 // type we're looking for, then there is another conversion step
3322 // we need to perform to produce a temporary of the right type
3323 // that we'll be binding to.
3324 ImplicitConversionSequence ICS;
3325 ICS.setStandard();
3326 ICS.Standard = Best->FinalConversion;
3327 T2 = ICS.Standard.getToType(2);
3328 Sequence.AddConversionSequenceStep(ICS, T2);
3329 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003330 Sequence.AddDerivedToBaseCastStep(
3331 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003333 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003334 else if (NewObjCConversion)
3335 Sequence.AddObjCObjectConversionStep(
3336 S.Context.getQualifiedType(T1,
3337 T2.getNonReferenceType().getQualifiers()));
3338
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003339 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003340 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003342 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3343 return OR_Success;
3344}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
Richard Smithc620f552011-10-19 16:55:56 +00003346static void CheckCXX98CompatAccessibleCopy(Sema &S,
3347 const InitializedEntity &Entity,
3348 Expr *CurInitExpr);
3349
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3351static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003352 const InitializedEntity &Entity,
3353 const InitializationKind &Kind,
3354 Expr *Initializer,
3355 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003356 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003357 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003358 Qualifiers T1Quals;
3359 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003360 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003361 Qualifiers T2Quals;
3362 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003363
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003364 // If the initializer is the address of an overloaded function, try
3365 // to resolve the overloaded function. If all goes well, T2 is the
3366 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003367 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3368 T1, Sequence))
3369 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003370
Sebastian Redl29526f02011-11-27 16:50:07 +00003371 // Delegate everything else to a subfunction.
3372 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3373 T1Quals, cv2T2, T2, T2Quals, Sequence);
3374}
3375
3376/// \brief Reference initialization without resolving overloaded functions.
3377static void TryReferenceInitializationCore(Sema &S,
3378 const InitializedEntity &Entity,
3379 const InitializationKind &Kind,
3380 Expr *Initializer,
3381 QualType cv1T1, QualType T1,
3382 Qualifiers T1Quals,
3383 QualType cv2T2, QualType T2,
3384 Qualifiers T2Quals,
3385 InitializationSequence &Sequence) {
3386 QualType DestType = Entity.getType();
3387 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003388 // Compute some basic properties of the types and the initializer.
3389 bool isLValueRef = DestType->isLValueReferenceType();
3390 bool isRValueRef = !isLValueRef;
3391 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003392 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003393 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003394 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003395 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003396 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003397 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003398
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003399 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003401 // "cv2 T2" as follows:
3402 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003404 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003405 // Note the analogous bullet points for rvlaue refs to functions. Because
3406 // there are no function rvalues in C++, rvalue refs to functions are treated
3407 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003408 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003409 bool T1Function = T1->isFunctionType();
3410 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003412 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003414 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003416 // reference-compatible with "cv2 T2," or
3417 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003420 // can occur. However, we do pay attention to whether it is a bit-field
3421 // to decide whether we're actually binding to a temporary created from
3422 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003423 if (DerivedToBase)
3424 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003426 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003427 else if (ObjCConversion)
3428 Sequence.AddObjCObjectConversionStep(
3429 S.Context.getQualifiedType(T1, T2Quals));
3430
Chandler Carruth04bdce62010-01-12 20:32:25 +00003431 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003432 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003433 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003434 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003435 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003436 return;
3437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
3439 // - has a class type (i.e., T2 is a class type), where T1 is not
3440 // reference-related to T2, and can be implicitly converted to an
3441 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3442 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003443 // applicable conversion functions (13.3.1.6) and choosing the best
3444 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003445 // If we have an rvalue ref to function type here, the rhs must be
3446 // an rvalue.
3447 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3448 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003450 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003451 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003452 Sequence);
3453 if (ConvOvlResult == OR_Success)
3454 return;
John McCall0d1da222010-01-12 00:44:57 +00003455 if (ConvOvlResult != OR_No_Viable_Function) {
3456 Sequence.SetOverloadFailure(
3457 InitializationSequence::FK_ReferenceInitOverloadFailed,
3458 ConvOvlResult);
3459 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003460 }
3461 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003462
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003464 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003465 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003466 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003467 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3468 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3469 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003470 Sequence.SetOverloadFailure(
3471 InitializationSequence::FK_ReferenceInitOverloadFailed,
3472 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003473 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003474 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003475 ? (RefRelationship == Sema::Ref_Related
3476 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3477 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3478 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003479
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003480 return;
3481 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003482
Douglas Gregor92e460e2011-01-20 16:44:54 +00003483 // - If the initializer expression
3484 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3485 // "cv1 T1" is reference-compatible with "cv2 T2"
3486 // Note: functions are handled below.
3487 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003488 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003490 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003491 (InitCategory.isXValue() ||
3492 (InitCategory.isPRValue() && T2->isRecordType()) ||
3493 (InitCategory.isPRValue() && T2->isArrayType()))) {
3494 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3495 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003496 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3497 // compiler the freedom to perform a copy here or bind to the
3498 // object, while C++0x requires that we bind directly to the
3499 // object. Hence, we always bind to the object without making an
3500 // extra copy. However, in C++03 requires that we check for the
3501 // presence of a suitable copy constructor:
3502 //
3503 // The constructor that would be used to make the copy shall
3504 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003505 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003506 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003507 else if (S.getLangOptions().CPlusPlus0x)
3508 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
Douglas Gregor92e460e2011-01-20 16:44:54 +00003511 if (DerivedToBase)
3512 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3513 ValueKind);
3514 else if (ObjCConversion)
3515 Sequence.AddObjCObjectConversionStep(
3516 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Douglas Gregor92e460e2011-01-20 16:44:54 +00003518 if (T1Quals != T2Quals)
3519 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003521 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
3525 // - has a class type (i.e., T2 is a class type), where T1 is not
3526 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003527 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3528 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003529 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003530 if (RefRelationship == Sema::Ref_Incompatible) {
3531 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3532 Kind, Initializer,
3533 /*AllowRValues=*/true,
3534 Sequence);
3535 if (ConvOvlResult)
3536 Sequence.SetOverloadFailure(
3537 InitializationSequence::FK_ReferenceInitOverloadFailed,
3538 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003540 return;
3541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3544 return;
3545 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003546
3547 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003548 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003550 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003551
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003552 // Determine whether we are allowed to call explicit constructors or
3553 // explicit conversion operators.
3554 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003555
3556 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3557
John McCall31168b02011-06-15 23:02:42 +00003558 ImplicitConversionSequence ICS
3559 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003560 /*SuppressUserConversions*/ false,
3561 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003562 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003563 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3564 /*AllowObjCWritebackConversion=*/false);
3565
3566 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003567 // FIXME: Use the conversion function set stored in ICS to turn
3568 // this into an overloading ambiguity diagnostic. However, we need
3569 // to keep that set as an OverloadCandidateSet rather than as some
3570 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003571 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3572 Sequence.SetOverloadFailure(
3573 InitializationSequence::FK_ReferenceInitOverloadFailed,
3574 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003575 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3576 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003577 else
3578 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003579 return;
John McCall31168b02011-06-15 23:02:42 +00003580 } else {
3581 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582 }
3583
3584 // [...] If T1 is reference-related to T2, cv1 must be the
3585 // same cv-qualification as, or greater cv-qualification
3586 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003587 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3588 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003590 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003591 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3592 return;
3593 }
3594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003596 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003598 InitCategory.isLValue()) {
3599 Sequence.SetFailed(
3600 InitializationSequence::FK_RValueReferenceBindingToLValue);
3601 return;
3602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3605 return;
3606}
3607
3608/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609/// (C++ [dcl.init.string], C99 6.7.8).
3610static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611 const InitializedEntity &Entity,
3612 const InitializationKind &Kind,
3613 Expr *Initializer,
3614 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003615 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003616}
3617
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003618/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003620 const InitializedEntity &Entity,
3621 const InitializationKind &Kind,
3622 InitializationSequence &Sequence) {
3623 // C++ [dcl.init]p5:
3624 //
3625 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003626 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003628 // -- if T is an array type, then each element is value-initialized;
3629 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3630 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003632 if (const RecordType *RT = T->getAs<RecordType>()) {
3633 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3634 // -- if T is a class type (clause 9) with a user-declared
3635 // constructor (12.1), then the default constructor for T is
3636 // called (and the initialization is ill-formed if T has no
3637 // accessible default constructor);
3638 //
3639 // FIXME: we really want to refer to a single subobject of the array,
3640 // but Entity doesn't have a way to capture that (yet).
3641 if (ClassDecl->hasUserDeclaredConstructor())
3642 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003643
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003644 // -- if T is a (possibly cv-qualified) non-union class type
3645 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003646 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003647 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003648 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003649 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003650 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003652 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003653 }
3654 }
3655
Douglas Gregor1b303932009-12-22 15:35:07 +00003656 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003657}
3658
Douglas Gregor85dabae2009-12-16 01:38:02 +00003659/// \brief Attempt default initialization (C++ [dcl.init]p6).
3660static void TryDefaultInitialization(Sema &S,
3661 const InitializedEntity &Entity,
3662 const InitializationKind &Kind,
3663 InitializationSequence &Sequence) {
3664 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665
Douglas Gregor85dabae2009-12-16 01:38:02 +00003666 // C++ [dcl.init]p6:
3667 // To default-initialize an object of type T means:
3668 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003669 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3670
Douglas Gregor85dabae2009-12-16 01:38:02 +00003671 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3672 // constructor for T is called (and the initialization is ill-formed if
3673 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003674 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003675 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3676 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Douglas Gregor85dabae2009-12-16 01:38:02 +00003679 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680
Douglas Gregor85dabae2009-12-16 01:38:02 +00003681 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003683 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003684 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003685 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003686 return;
3687 }
3688
3689 // If the destination type has a lifetime property, zero-initialize it.
3690 if (DestType.getQualifiers().hasObjCLifetime()) {
3691 Sequence.AddZeroInitializationStep(Entity.getType());
3692 return;
3693 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003694}
3695
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003696/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3697/// which enumerates all conversion functions and performs overload resolution
3698/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003700 const InitializedEntity &Entity,
3701 const InitializationKind &Kind,
3702 Expr *Initializer,
3703 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003704 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003705 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3706 QualType SourceType = Initializer->getType();
3707 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3708 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709
Douglas Gregor540c3b02009-12-14 17:27:33 +00003710 // Build the candidate set directly in the initialization sequence
3711 // structure, so that it will persist if we fail.
3712 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3713 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714
Douglas Gregor540c3b02009-12-14 17:27:33 +00003715 // Determine whether we are allowed to call explicit constructors or
3716 // explicit conversion operators.
3717 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718
Douglas Gregor540c3b02009-12-14 17:27:33 +00003719 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3720 // The type we're converting to is a class type. Enumerate its constructors
3721 // to see if there is a suitable conversion.
3722 CXXRecordDecl *DestRecordDecl
3723 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724
Douglas Gregord9848152010-04-26 14:36:57 +00003725 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003727 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003728 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003729 Con != ConEnd; ++Con) {
3730 NamedDecl *D = *Con;
3731 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Douglas Gregord9848152010-04-26 14:36:57 +00003733 // Find the constructor (which may be a template).
3734 CXXConstructorDecl *Constructor = 0;
3735 FunctionTemplateDecl *ConstructorTmpl
3736 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003737 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003738 Constructor = cast<CXXConstructorDecl>(
3739 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003740 else
Douglas Gregord9848152010-04-26 14:36:57 +00003741 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Douglas Gregord9848152010-04-26 14:36:57 +00003743 if (!Constructor->isInvalidDecl() &&
3744 Constructor->isConvertingConstructor(AllowExplicit)) {
3745 if (ConstructorTmpl)
3746 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3747 /*ExplicitArgs*/ 0,
3748 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003749 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003750 else
3751 S.AddOverloadCandidate(Constructor, FoundDecl,
3752 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003753 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755 }
Douglas Gregord9848152010-04-26 14:36:57 +00003756 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003757 }
Eli Friedman78275202009-12-19 08:11:05 +00003758
3759 SourceLocation DeclLoc = Initializer->getLocStart();
3760
Douglas Gregor540c3b02009-12-14 17:27:33 +00003761 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3762 // The type we're converting from is a class type, enumerate its conversion
3763 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003764
Eli Friedman4afe9a32009-12-20 22:12:03 +00003765 // We can only enumerate the conversion functions for a complete type; if
3766 // the type isn't complete, simply skip this step.
3767 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3768 CXXRecordDecl *SourceRecordDecl
3769 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
John McCallad371252010-01-20 00:46:10 +00003771 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003772 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003773 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003775 I != E; ++I) {
3776 NamedDecl *D = *I;
3777 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3778 if (isa<UsingShadowDecl>(D))
3779 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780
Eli Friedman4afe9a32009-12-20 22:12:03 +00003781 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3782 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003783 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003784 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003785 else
John McCallda4458e2010-03-31 01:36:47 +00003786 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Eli Friedman4afe9a32009-12-20 22:12:03 +00003788 if (AllowExplicit || !Conv->isExplicit()) {
3789 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003790 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003791 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003792 CandidateSet);
3793 else
John McCalla0296f72010-03-19 07:35:19 +00003794 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003795 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003796 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003797 }
3798 }
3799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
3801 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003802 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003803 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003804 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003805 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003806 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003807 Result);
3808 return;
3809 }
John McCall0d1da222010-01-12 00:44:57 +00003810
Douglas Gregor540c3b02009-12-14 17:27:33 +00003811 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003812 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003813 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregor540c3b02009-12-14 17:27:33 +00003815 if (isa<CXXConstructorDecl>(Function)) {
3816 // Add the user-defined conversion step. Any cv-qualification conversion is
3817 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003818 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3819 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003820 return;
3821 }
3822
3823 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003824 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003825 if (ConvType->getAs<RecordType>()) {
3826 // If we're converting to a class type, there may be an copy if
3827 // the resulting temporary object (possible to create an object of
3828 // a base class type). That copy is not a separate conversion, so
3829 // we just make a note of the actual destination type (possibly a
3830 // base class of the type returned by the conversion function) and
3831 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003832 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3833 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003834 return;
3835 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003836
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003837 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3838 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor5ab11652010-04-17 22:01:05 +00003840 // If the conversion following the call to the conversion function
3841 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003842 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3843 Best->FinalConversion.Third) {
3844 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003845 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003846 ICS.Standard = Best->FinalConversion;
3847 Sequence.AddConversionSequenceStep(ICS, DestType);
3848 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003849}
3850
John McCall31168b02011-06-15 23:02:42 +00003851/// The non-zero enum values here are indexes into diagnostic alternatives.
3852enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3853
3854/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003855static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3856 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003857 // Skip parens.
3858 e = e->IgnoreParens();
3859
3860 // Skip address-of nodes.
3861 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3862 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003863 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003864
3865 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003866 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3867 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003868 case CK_Dependent:
3869 case CK_BitCast:
3870 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003871 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003872 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003873
3874 case CK_ArrayToPointerDecay:
3875 return IIK_nonscalar;
3876
3877 case CK_NullToPointer:
3878 return IIK_okay;
3879
3880 default:
3881 break;
3882 }
3883
3884 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003885 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3886 if (!isAddressOf) return IIK_nonlocal;
3887
3888 VarDecl *var;
3889 if (isa<DeclRefExpr>(e)) {
3890 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3891 if (!var) return IIK_nonlocal;
3892 } else {
3893 var = cast<BlockDeclRefExpr>(e)->getDecl();
3894 }
3895
3896 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003897
3898 // If we have a conditional operator, check both sides.
3899 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003900 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003901 return iik;
3902
John McCall63f84442011-06-27 23:59:58 +00003903 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003904
3905 // These are never scalar.
3906 } else if (isa<ArraySubscriptExpr>(e)) {
3907 return IIK_nonscalar;
3908
3909 // Otherwise, it needs to be a null pointer constant.
3910 } else {
3911 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3912 ? IIK_okay : IIK_nonlocal);
3913 }
3914
3915 return IIK_nonlocal;
3916}
3917
3918/// Check whether the given expression is a valid operand for an
3919/// indirect copy/restore.
3920static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3921 assert(src->isRValue());
3922
John McCall63f84442011-06-27 23:59:58 +00003923 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003924 if (iik == IIK_okay) return;
3925
3926 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3927 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3928 << src->getSourceRange();
3929}
3930
Douglas Gregore2f943b2011-02-22 18:29:51 +00003931/// \brief Determine whether we have compatible array types for the
3932/// purposes of GNU by-copy array initialization.
3933static bool hasCompatibleArrayTypes(ASTContext &Context,
3934 const ArrayType *Dest,
3935 const ArrayType *Source) {
3936 // If the source and destination array types are equivalent, we're
3937 // done.
3938 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3939 return true;
3940
3941 // Make sure that the element types are the same.
3942 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3943 return false;
3944
3945 // The only mismatch we allow is when the destination is an
3946 // incomplete array type and the source is a constant array type.
3947 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3948}
3949
John McCall31168b02011-06-15 23:02:42 +00003950static bool tryObjCWritebackConversion(Sema &S,
3951 InitializationSequence &Sequence,
3952 const InitializedEntity &Entity,
3953 Expr *Initializer) {
3954 bool ArrayDecay = false;
3955 QualType ArgType = Initializer->getType();
3956 QualType ArgPointee;
3957 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3958 ArrayDecay = true;
3959 ArgPointee = ArgArrayType->getElementType();
3960 ArgType = S.Context.getPointerType(ArgPointee);
3961 }
3962
3963 // Handle write-back conversion.
3964 QualType ConvertedArgType;
3965 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3966 ConvertedArgType))
3967 return false;
3968
3969 // We should copy unless we're passing to an argument explicitly
3970 // marked 'out'.
3971 bool ShouldCopy = true;
3972 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3973 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3974
3975 // Do we need an lvalue conversion?
3976 if (ArrayDecay || Initializer->isGLValue()) {
3977 ImplicitConversionSequence ICS;
3978 ICS.setStandard();
3979 ICS.Standard.setAsIdentityConversion();
3980
3981 QualType ResultType;
3982 if (ArrayDecay) {
3983 ICS.Standard.First = ICK_Array_To_Pointer;
3984 ResultType = S.Context.getPointerType(ArgPointee);
3985 } else {
3986 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3987 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3988 }
3989
3990 Sequence.AddConversionSequenceStep(ICS, ResultType);
3991 }
3992
3993 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3994 return true;
3995}
3996
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003997InitializationSequence::InitializationSequence(Sema &S,
3998 const InitializedEntity &Entity,
3999 const InitializationKind &Kind,
4000 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00004001 unsigned NumArgs)
4002 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004003 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004005 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006 // The semantics of initializers are as follows. The destination type is
4007 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004008 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004009 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004010 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004011 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004013 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004014 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
4015 SequenceKind = DependentSequence;
4016 return;
4017 }
4018
Sebastian Redld201edf2011-06-05 13:59:11 +00004019 // Almost everything is a normal sequence.
4020 setSequenceKind(NormalSequence);
4021
John McCalled75c092010-12-07 22:54:16 +00004022 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00004023 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00004024 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00004025 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4026 if (result.isInvalid()) {
4027 SetFailed(FK_PlaceholderType);
4028 return;
John McCall4124c492011-10-17 18:40:02 +00004029 }
John McCalld5c98ae2011-11-15 01:35:18 +00004030 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00004031 }
John McCalled75c092010-12-07 22:54:16 +00004032
John McCall4124c492011-10-17 18:40:02 +00004033
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 QualType SourceType;
4035 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004036 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004037 Initializer = Args[0];
4038 if (!isa<InitListExpr>(Initializer))
4039 SourceType = Initializer->getType();
4040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041
4042 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004043 // list-initialized (8.5.4).
4044 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004045 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004046 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049 // - If the destination type is a reference type, see 8.5.3.
4050 if (DestType->isReferenceType()) {
4051 // C++0x [dcl.init.ref]p1:
4052 // A variable declared to be a T& or T&&, that is, "reference to type T"
4053 // (8.3.2), shall be initialized by an object, or function, of type T or
4054 // by an object that can be converted into a T.
4055 // (Therefore, multiple arguments are not permitted.)
4056 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004057 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004058 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004059 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004060 return;
4061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004063 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004064 if (Kind.getKind() == InitializationKind::IK_Value ||
4065 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004066 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004067 return;
4068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069
Douglas Gregor85dabae2009-12-16 01:38:02 +00004070 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004071 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004072 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004073 return;
4074 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004075
John McCall66884dd2011-02-21 07:22:22 +00004076 // - If the destination type is an array of characters, an array of
4077 // char16_t, an array of char32_t, or an array of wchar_t, and the
4078 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004080 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004081 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004082 if (Initializer && isa<VariableArrayType>(DestAT)) {
4083 SetFailed(FK_VariableLengthArrayHasInitializer);
4084 return;
4085 }
4086
Douglas Gregore2f943b2011-02-22 18:29:51 +00004087 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004088 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004089 return;
4090 }
4091
Douglas Gregore2f943b2011-02-22 18:29:51 +00004092 // Note: as an GNU C extension, we allow initialization of an
4093 // array from a compound literal that creates an array of the same
4094 // type, so long as the initializer has no side effects.
4095 if (!S.getLangOptions().CPlusPlus && Initializer &&
4096 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4097 Initializer->getType()->isArrayType()) {
4098 const ArrayType *SourceAT
4099 = Context.getAsArrayType(Initializer->getType());
4100 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004101 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004102 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004103 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004104 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004105 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004106 }
4107 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004108 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004109 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004110 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004112 return;
4113 }
Eli Friedman78275202009-12-19 08:11:05 +00004114
John McCall31168b02011-06-15 23:02:42 +00004115 // Determine whether we should consider writeback conversions for
4116 // Objective-C ARC.
4117 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4118 Entity.getKind() == InitializedEntity::EK_Parameter;
4119
4120 // We're at the end of the line for C: it's either a write-back conversion
4121 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004122 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004123 // If allowed, check whether this is an Objective-C writeback conversion.
4124 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004125 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004126 return;
4127 }
4128
4129 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004130 AddCAssignmentStep(DestType);
4131 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004132 return;
4133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134
John McCall31168b02011-06-15 23:02:42 +00004135 assert(S.getLangOptions().CPlusPlus);
4136
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004137 // - If the destination type is a (possibly cv-qualified) class type:
4138 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139 // - If the initialization is direct-initialization, or if it is
4140 // copy-initialization where the cv-unqualified version of the
4141 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004142 // class of the destination, constructors are considered. [...]
4143 if (Kind.getKind() == InitializationKind::IK_Direct ||
4144 (Kind.getKind() == InitializationKind::IK_Copy &&
4145 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4146 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004148 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004149 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004150 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152 // used) to a derived class thereof are enumerated as described in
4153 // 13.3.1.4, and the best one is chosen through overload resolution
4154 // (13.3).
4155 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004156 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004157 return;
4158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159
Douglas Gregor85dabae2009-12-16 01:38:02 +00004160 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004161 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004162 return;
4163 }
4164 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
4166 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004167 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004168 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004169 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4170 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004171 return;
4172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004174 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004175 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004176 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004178 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004179
4180 ImplicitConversionSequence ICS
4181 = S.TryImplicitConversion(Initializer, Entity.getType(),
4182 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004183 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004184 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004185 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4186 allowObjCWritebackConversion);
4187
4188 if (ICS.isStandard() &&
4189 ICS.Standard.Second == ICK_Writeback_Conversion) {
4190 // Objective-C ARC writeback conversion.
4191
4192 // We should copy unless we're passing to an argument explicitly
4193 // marked 'out'.
4194 bool ShouldCopy = true;
4195 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4196 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4197
4198 // If there was an lvalue adjustment, add it as a separate conversion.
4199 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4200 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4201 ImplicitConversionSequence LvalueICS;
4202 LvalueICS.setStandard();
4203 LvalueICS.Standard.setAsIdentityConversion();
4204 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4205 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004206 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004207 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004208
4209 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004210 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004211 DeclAccessPair dap;
4212 if (Initializer->getType() == Context.OverloadTy &&
4213 !S.ResolveAddressOfOverloadedFunction(Initializer
4214 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004215 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004216 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004217 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004218 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004219 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004220
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004221 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004222 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004223}
4224
4225InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004226 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004227 StepEnd = Steps.end();
4228 Step != StepEnd; ++Step)
4229 Step->Destroy();
4230}
4231
4232//===----------------------------------------------------------------------===//
4233// Perform initialization
4234//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004236getAssignmentAction(const InitializedEntity &Entity) {
4237 switch(Entity.getKind()) {
4238 case InitializedEntity::EK_Variable:
4239 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004240 case InitializedEntity::EK_Exception:
4241 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004242 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004243 return Sema::AA_Initializing;
4244
4245 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004247 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4248 return Sema::AA_Sending;
4249
Douglas Gregore1314a62009-12-18 05:02:21 +00004250 return Sema::AA_Passing;
4251
4252 case InitializedEntity::EK_Result:
4253 return Sema::AA_Returning;
4254
Douglas Gregore1314a62009-12-18 05:02:21 +00004255 case InitializedEntity::EK_Temporary:
4256 // FIXME: Can we tell apart casting vs. converting?
4257 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregore1314a62009-12-18 05:02:21 +00004259 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004260 case InitializedEntity::EK_ArrayElement:
4261 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004262 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004263 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004264 return Sema::AA_Initializing;
4265 }
4266
4267 return Sema::AA_Converting;
4268}
4269
Douglas Gregor95562572010-04-24 23:45:46 +00004270/// \brief Whether we should binding a created object as a temporary when
4271/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004272static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004273 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004274 case InitializedEntity::EK_ArrayElement:
4275 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004276 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004277 case InitializedEntity::EK_New:
4278 case InitializedEntity::EK_Variable:
4279 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004280 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004281 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004282 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004283 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004284 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004285 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286
Douglas Gregore1314a62009-12-18 05:02:21 +00004287 case InitializedEntity::EK_Parameter:
4288 case InitializedEntity::EK_Temporary:
4289 return true;
4290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
Douglas Gregore1314a62009-12-18 05:02:21 +00004292 llvm_unreachable("missed an InitializedEntity kind?");
4293}
4294
Douglas Gregor95562572010-04-24 23:45:46 +00004295/// \brief Whether the given entity, when initialized with an object
4296/// created for that initialization, requires destruction.
4297static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4298 switch (Entity.getKind()) {
4299 case InitializedEntity::EK_Member:
4300 case InitializedEntity::EK_Result:
4301 case InitializedEntity::EK_New:
4302 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004303 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004304 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004305 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004306 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004307 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor95562572010-04-24 23:45:46 +00004309 case InitializedEntity::EK_Variable:
4310 case InitializedEntity::EK_Parameter:
4311 case InitializedEntity::EK_Temporary:
4312 case InitializedEntity::EK_ArrayElement:
4313 case InitializedEntity::EK_Exception:
4314 return true;
4315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316
4317 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004318}
4319
Richard Smithc620f552011-10-19 16:55:56 +00004320/// \brief Look for copy and move constructors and constructor templates, for
4321/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4322static void LookupCopyAndMoveConstructors(Sema &S,
4323 OverloadCandidateSet &CandidateSet,
4324 CXXRecordDecl *Class,
4325 Expr *CurInitExpr) {
4326 DeclContext::lookup_iterator Con, ConEnd;
4327 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4328 Con != ConEnd; ++Con) {
4329 CXXConstructorDecl *Constructor = 0;
4330
4331 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4332 // Handle copy/moveconstructors, only.
4333 if (!Constructor || Constructor->isInvalidDecl() ||
4334 !Constructor->isCopyOrMoveConstructor() ||
4335 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4336 continue;
4337
4338 DeclAccessPair FoundDecl
4339 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4340 S.AddOverloadCandidate(Constructor, FoundDecl,
4341 &CurInitExpr, 1, CandidateSet);
4342 continue;
4343 }
4344
4345 // Handle constructor templates.
4346 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4347 if (ConstructorTmpl->isInvalidDecl())
4348 continue;
4349
4350 Constructor = cast<CXXConstructorDecl>(
4351 ConstructorTmpl->getTemplatedDecl());
4352 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4353 continue;
4354
4355 // FIXME: Do we need to limit this to copy-constructor-like
4356 // candidates?
4357 DeclAccessPair FoundDecl
4358 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4359 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4360 &CurInitExpr, 1, CandidateSet, true);
4361 }
4362}
4363
4364/// \brief Get the location at which initialization diagnostics should appear.
4365static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4366 Expr *Initializer) {
4367 switch (Entity.getKind()) {
4368 case InitializedEntity::EK_Result:
4369 return Entity.getReturnLoc();
4370
4371 case InitializedEntity::EK_Exception:
4372 return Entity.getThrowLoc();
4373
4374 case InitializedEntity::EK_Variable:
4375 return Entity.getDecl()->getLocation();
4376
4377 case InitializedEntity::EK_ArrayElement:
4378 case InitializedEntity::EK_Member:
4379 case InitializedEntity::EK_Parameter:
4380 case InitializedEntity::EK_Temporary:
4381 case InitializedEntity::EK_New:
4382 case InitializedEntity::EK_Base:
4383 case InitializedEntity::EK_Delegating:
4384 case InitializedEntity::EK_VectorElement:
4385 case InitializedEntity::EK_ComplexElement:
4386 case InitializedEntity::EK_BlockElement:
4387 return Initializer->getLocStart();
4388 }
4389 llvm_unreachable("missed an InitializedEntity kind?");
4390}
4391
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004392/// \brief Make a (potentially elidable) temporary copy of the object
4393/// provided by the given initializer by calling the appropriate copy
4394/// constructor.
4395///
4396/// \param S The Sema object used for type-checking.
4397///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004398/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004399/// the type of the initializer expression or a superclass thereof.
4400///
4401/// \param Enter The entity being initialized.
4402///
4403/// \param CurInit The initializer expression.
4404///
4405/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4406/// is permitted in C++03 (but not C++0x) when binding a reference to
4407/// an rvalue.
4408///
4409/// \returns An expression that copies the initializer expression into
4410/// a temporary object, or an error expression if a copy could not be
4411/// created.
John McCalldadc5752010-08-24 06:29:42 +00004412static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004413 QualType T,
4414 const InitializedEntity &Entity,
4415 ExprResult CurInit,
4416 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004417 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004418 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004420 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004421 Class = cast<CXXRecordDecl>(Record->getDecl());
4422 if (!Class)
4423 return move(CurInit);
4424
Douglas Gregor5d369002011-01-21 18:05:27 +00004425 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004426 // When certain criteria are met, an implementation is allowed to
4427 // omit the copy/move construction of a class object, even if the
4428 // copy/move constructor and/or destructor for the object have
4429 // side effects. [...]
4430 // - when a temporary class object that has not been bound to a
4431 // reference (12.2) would be copied/moved to a class object
4432 // with the same cv-unqualified type, the copy/move operation
4433 // can be omitted by constructing the temporary object
4434 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004436 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004437 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004439 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004440 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004441 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004442
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004444 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4445 return move(CurInit);
4446
Douglas Gregorf282a762011-01-21 19:38:21 +00004447 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004448 // Only consider constructors and constructor templates. Per
4449 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4450 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004451 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004452 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004454 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4455
Douglas Gregore1314a62009-12-18 05:02:21 +00004456 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004457 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004458 case OR_Success:
4459 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregore1314a62009-12-18 05:02:21 +00004461 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004462 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4463 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4464 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004465 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004466 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004467 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004468 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004469 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004470 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
Douglas Gregore1314a62009-12-18 05:02:21 +00004472 case OR_Ambiguous:
4473 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004474 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004475 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004476 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004477 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregore1314a62009-12-18 05:02:21 +00004479 case OR_Deleted:
4480 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004481 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004482 << CurInitExpr->getSourceRange();
4483 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004484 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004485 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004486 }
4487
Douglas Gregor5ab11652010-04-17 22:01:05 +00004488 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004489 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004490 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004491
Anders Carlssona01874b2010-04-21 18:47:17 +00004492 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004493 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004494
4495 if (IsExtraneousCopy) {
4496 // If this is a totally extraneous copy for C++03 reference
4497 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004498 // expression. We don't generate an (elided) copy operation here
4499 // because doing so would require us to pass down a flag to avoid
4500 // infinite recursion, where each step adds another extraneous,
4501 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004502
Douglas Gregor30b52772010-04-18 07:57:34 +00004503 // Instantiate the default arguments of any extra parameters in
4504 // the selected copy constructor, as if we were going to create a
4505 // proper call to the copy constructor.
4506 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4507 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4508 if (S.RequireCompleteType(Loc, Parm->getType(),
4509 S.PDiag(diag::err_call_incomplete_argument)))
4510 break;
4511
4512 // Build the default argument expression; we don't actually care
4513 // if this succeeds or not, because this routine will complain
4514 // if there was a problem.
4515 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4516 }
4517
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004518 return S.Owned(CurInitExpr);
4519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Chandler Carruth30141632011-02-25 19:41:05 +00004521 S.MarkDeclarationReferenced(Loc, Constructor);
4522
Douglas Gregor5ab11652010-04-17 22:01:05 +00004523 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004524 // constructor call (we might have derived-to-base conversions, or
4525 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004526 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004527 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004528 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004529
Douglas Gregord0ace022010-04-25 00:55:24 +00004530 // Actually perform the constructor call.
4531 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004532 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004533 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004534 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004535 CXXConstructExpr::CK_Complete,
4536 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537
Douglas Gregord0ace022010-04-25 00:55:24 +00004538 // If we're supposed to bind temporaries, do so.
4539 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4540 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4541 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004542}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543
Richard Smithc620f552011-10-19 16:55:56 +00004544/// \brief Check whether elidable copy construction for binding a reference to
4545/// a temporary would have succeeded if we were building in C++98 mode, for
4546/// -Wc++98-compat.
4547static void CheckCXX98CompatAccessibleCopy(Sema &S,
4548 const InitializedEntity &Entity,
4549 Expr *CurInitExpr) {
4550 assert(S.getLangOptions().CPlusPlus0x);
4551
4552 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4553 if (!Record)
4554 return;
4555
4556 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4557 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4558 == DiagnosticsEngine::Ignored)
4559 return;
4560
4561 // Find constructors which would have been considered.
4562 OverloadCandidateSet CandidateSet(Loc);
4563 LookupCopyAndMoveConstructors(
4564 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4565
4566 // Perform overload resolution.
4567 OverloadCandidateSet::iterator Best;
4568 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4569
4570 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4571 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4572 << CurInitExpr->getSourceRange();
4573
4574 switch (OR) {
4575 case OR_Success:
4576 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4577 Best->FoundDecl.getAccess(), Diag);
4578 // FIXME: Check default arguments as far as that's possible.
4579 break;
4580
4581 case OR_No_Viable_Function:
4582 S.Diag(Loc, Diag);
4583 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4584 break;
4585
4586 case OR_Ambiguous:
4587 S.Diag(Loc, Diag);
4588 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4589 break;
4590
4591 case OR_Deleted:
4592 S.Diag(Loc, Diag);
4593 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4594 << 1 << Best->Function->isDeleted();
4595 break;
4596 }
4597}
4598
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004599void InitializationSequence::PrintInitLocationNote(Sema &S,
4600 const InitializedEntity &Entity) {
4601 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4602 if (Entity.getDecl()->getLocation().isInvalid())
4603 return;
4604
4605 if (Entity.getDecl()->getDeclName())
4606 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4607 << Entity.getDecl()->getDeclName();
4608 else
4609 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4610 }
4611}
4612
Sebastian Redl112aa822011-07-14 19:07:55 +00004613static bool isReferenceBinding(const InitializationSequence::Step &s) {
4614 return s.Kind == InitializationSequence::SK_BindReference ||
4615 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4616}
4617
Sebastian Redled2e5322011-12-22 14:44:04 +00004618static ExprResult
4619PerformConstructorInitialization(Sema &S,
4620 const InitializedEntity &Entity,
4621 const InitializationKind &Kind,
4622 MultiExprArg Args,
4623 const InitializationSequence::Step& Step,
4624 bool &ConstructorInitRequiresZeroInit) {
4625 unsigned NumArgs = Args.size();
4626 CXXConstructorDecl *Constructor
4627 = cast<CXXConstructorDecl>(Step.Function.Function);
4628 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4629
4630 // Build a call to the selected constructor.
4631 ASTOwningVector<Expr*> ConstructorArgs(S);
4632 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4633 ? Kind.getEqualLoc()
4634 : Kind.getLocation();
4635
4636 if (Kind.getKind() == InitializationKind::IK_Default) {
4637 // Force even a trivial, implicit default constructor to be
4638 // semantically checked. We do this explicitly because we don't build
4639 // the definition for completely trivial constructors.
4640 CXXRecordDecl *ClassDecl = Constructor->getParent();
4641 assert(ClassDecl && "No parent class for constructor.");
4642 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4643 ClassDecl->hasTrivialDefaultConstructor() &&
4644 !Constructor->isUsed(false))
4645 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4646 }
4647
4648 ExprResult CurInit = S.Owned((Expr *)0);
4649
4650 // Determine the arguments required to actually perform the constructor
4651 // call.
4652 if (S.CompleteConstructorCall(Constructor, move(Args),
4653 Loc, ConstructorArgs))
4654 return ExprError();
4655
4656
4657 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4658 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4659 (Kind.getKind() == InitializationKind::IK_Direct ||
4660 Kind.getKind() == InitializationKind::IK_Value)) {
4661 // An explicitly-constructed temporary, e.g., X(1, 2).
4662 unsigned NumExprs = ConstructorArgs.size();
4663 Expr **Exprs = (Expr **)ConstructorArgs.take();
4664 S.MarkDeclarationReferenced(Loc, Constructor);
4665 S.DiagnoseUseOfDecl(Constructor, Loc);
4666
4667 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4668 if (!TSInfo)
4669 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4670
4671 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4672 Constructor,
4673 TSInfo,
4674 Exprs,
4675 NumExprs,
4676 Kind.getParenRange(),
4677 HadMultipleCandidates,
4678 ConstructorInitRequiresZeroInit));
4679 } else {
4680 CXXConstructExpr::ConstructionKind ConstructKind =
4681 CXXConstructExpr::CK_Complete;
4682
4683 if (Entity.getKind() == InitializedEntity::EK_Base) {
4684 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4685 CXXConstructExpr::CK_VirtualBase :
4686 CXXConstructExpr::CK_NonVirtualBase;
4687 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4688 ConstructKind = CXXConstructExpr::CK_Delegating;
4689 }
4690
4691 // Only get the parenthesis range if it is a direct construction.
4692 SourceRange parenRange =
4693 Kind.getKind() == InitializationKind::IK_Direct ?
4694 Kind.getParenRange() : SourceRange();
4695
4696 // If the entity allows NRVO, mark the construction as elidable
4697 // unconditionally.
4698 if (Entity.allowsNRVO())
4699 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4700 Constructor, /*Elidable=*/true,
4701 move_arg(ConstructorArgs),
4702 HadMultipleCandidates,
4703 ConstructorInitRequiresZeroInit,
4704 ConstructKind,
4705 parenRange);
4706 else
4707 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4708 Constructor,
4709 move_arg(ConstructorArgs),
4710 HadMultipleCandidates,
4711 ConstructorInitRequiresZeroInit,
4712 ConstructKind,
4713 parenRange);
4714 }
4715 if (CurInit.isInvalid())
4716 return ExprError();
4717
4718 // Only check access if all of that succeeded.
4719 S.CheckConstructorAccess(Loc, Constructor, Entity,
4720 Step.Function.FoundDecl.getAccess());
4721 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4722
4723 if (shouldBindAsTemporary(Entity))
4724 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4725
4726 return move(CurInit);
4727}
4728
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004730InitializationSequence::Perform(Sema &S,
4731 const InitializedEntity &Entity,
4732 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004733 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004734 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004735 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004736 unsigned NumArgs = Args.size();
4737 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004738 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
Sebastian Redld201edf2011-06-05 13:59:11 +00004741 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004742 // If the declaration is a non-dependent, incomplete array type
4743 // that has an initializer, then its type will be completed once
4744 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004745 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004746 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004747 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004748 if (const IncompleteArrayType *ArrayT
4749 = S.Context.getAsIncompleteArrayType(DeclType)) {
4750 // FIXME: We don't currently have the ability to accurately
4751 // compute the length of an initializer list without
4752 // performing full type-checking of the initializer list
4753 // (since we have to determine where braces are implicitly
4754 // introduced and such). So, we fall back to making the array
4755 // type a dependently-sized array type with no specified
4756 // bound.
4757 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4758 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004759
Douglas Gregor51e77d52009-12-10 17:56:55 +00004760 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004761 if (DeclaratorDecl *DD = Entity.getDecl()) {
4762 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4763 TypeLoc TL = TInfo->getTypeLoc();
4764 if (IncompleteArrayTypeLoc *ArrayLoc
4765 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4766 Brackets = ArrayLoc->getBracketsRange();
4767 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004768 }
4769
4770 *ResultType
4771 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4772 /*NumElts=*/0,
4773 ArrayT->getSizeModifier(),
4774 ArrayT->getIndexTypeCVRQualifiers(),
4775 Brackets);
4776 }
4777
4778 }
4779 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004780 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4781 Kind.isExplicitCast());
4782 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004783 }
4784
Sebastian Redld201edf2011-06-05 13:59:11 +00004785 // No steps means no initialization.
4786 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004787 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004788
Douglas Gregor1b303932009-12-22 15:35:07 +00004789 QualType DestType = Entity.getType().getNonReferenceType();
4790 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004791 // the same as Entity.getDecl()->getType() in cases involving type merging,
4792 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004793 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004794 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004795 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004796
John McCalldadc5752010-08-24 06:29:42 +00004797 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004800 // grab the only argument out the Args and place it into the "current"
4801 // initializer.
4802 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004803 case SK_ResolveAddressOfOverloadedFunction:
4804 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004805 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004806 case SK_CastDerivedToBaseLValue:
4807 case SK_BindReference:
4808 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004809 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004810 case SK_UserConversion:
4811 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004812 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004813 case SK_QualificationConversionRValue:
4814 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004815 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004816 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004817 case SK_UnwrapInitList:
4818 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004819 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004820 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004821 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004822 case SK_ArrayInit:
4823 case SK_PassByIndirectCopyRestore:
4824 case SK_PassByIndirectRestore:
4825 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004826 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004827 CurInit = Args.get()[0];
4828 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004829 break;
John McCall34376a62010-12-04 03:47:34 +00004830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831
Douglas Gregore1314a62009-12-18 05:02:21 +00004832 case SK_ConstructorInitialization:
4833 case SK_ZeroInitialization:
4834 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836
4837 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004838 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004839 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004840 for (step_iterator Step = step_begin(), StepEnd = step_end();
4841 Step != StepEnd; ++Step) {
4842 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004843 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
John Wiegley01296292011-04-08 18:41:53 +00004845 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004847 switch (Step->Kind) {
4848 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004850 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004851 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004852 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004853 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004854 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004855 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004856 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004857
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004858 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004859 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004860 case SK_CastDerivedToBaseLValue: {
4861 // We have a derived-to-base cast that produces either an rvalue or an
4862 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
John McCallcf142162010-08-07 06:22:56 +00004864 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004865
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866 // Casts to inaccessible base classes are allowed with C-style casts.
4867 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4868 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004869 CurInit.get()->getLocStart(),
4870 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004871 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
Douglas Gregor88d292c2010-05-13 16:44:06 +00004874 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4875 QualType T = SourceType;
4876 if (const PointerType *Pointer = T->getAs<PointerType>())
4877 T = Pointer->getPointeeType();
4878 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004879 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004880 cast<CXXRecordDecl>(RecordTy->getDecl()));
4881 }
4882
John McCall2536c6d2010-08-25 10:28:54 +00004883 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004884 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004885 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004886 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004887 VK_XValue :
4888 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004889 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4890 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004891 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004892 CurInit.get(),
4893 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004894 break;
4895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004898 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004899 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4900 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004901 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004902 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004903 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004904 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004905 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004906 }
Anders Carlssona91be642010-01-29 02:47:33 +00004907
John Wiegley01296292011-04-08 18:41:53 +00004908 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004909 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004910 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4911 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004912 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004913 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004914 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004917 // Reference binding does not have any corresponding ASTs.
4918
4919 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004920 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004921 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004923 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004924
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004925 case SK_BindReferenceToTemporary:
4926 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004927 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004928 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004929
Douglas Gregorfe314812011-06-21 17:03:29 +00004930 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004931 CurInit = new (S.Context) MaterializeTemporaryExpr(
4932 Entity.getType().getNonReferenceType(),
4933 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004934 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004935
4936 // If we're binding to an Objective-C object that has lifetime, we
4937 // need cleanups.
4938 if (S.getLangOptions().ObjCAutoRefCount &&
4939 CurInit.get()->getType()->isObjCLifetimeType())
4940 S.ExprNeedsCleanups = true;
4941
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004942 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004944 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004946 /*IsExtraneousCopy=*/true);
4947 break;
4948
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004949 case SK_UserConversion: {
4950 // We have a user-defined conversion that invokes either a constructor
4951 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004952 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004953 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004954 FunctionDecl *Fn = Step->Function.Function;
4955 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004956 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004957 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004958 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004959 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004960 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004961 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004962 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004963
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004964 // Determine the arguments required to actually perform the constructor
4965 // call.
John Wiegley01296292011-04-08 18:41:53 +00004966 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004967 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004968 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004969 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004970 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004971
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004972 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004974 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004975 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004976 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004977 CXXConstructExpr::CK_Complete,
4978 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004979 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004980 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004981
Anders Carlssona01874b2010-04-21 18:47:17 +00004982 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004983 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004984 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
John McCalle3027922010-08-25 11:45:40 +00004986 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004987 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4988 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4989 S.IsDerivedFrom(SourceType, Class))
4990 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004991
Douglas Gregor95562572010-04-24 23:45:46 +00004992 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004993 } else {
4994 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004995 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004996 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004997 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004998 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
5000 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005001 // derived-to-base conversion? I believe the answer is "no", because
5002 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005003 ExprResult CurInitExprRes =
5004 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5005 FoundFn, Conversion);
5006 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005007 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005008 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005010 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005011 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5012 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005013 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005014 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015
John McCalle3027922010-08-25 11:45:40 +00005016 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017
Douglas Gregor95562572010-04-24 23:45:46 +00005018 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020
Sebastian Redl112aa822011-07-14 19:07:55 +00005021 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005022 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5023
5024 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005025 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005026 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005028 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005029 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005030 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00005031 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
5032 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005033 }
5034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
John McCallcf142162010-08-07 06:22:56 +00005036 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005037 CurInit.get()->getType(),
5038 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005039 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005040 if (MaybeBindToTemp)
5041 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005042 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005043 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5044 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005045 break;
5046 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005048 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005049 case SK_QualificationConversionXValue:
5050 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005051 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005052 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005053 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005054 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005055 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005056 VK_XValue :
5057 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005058 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005059 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005060 }
5061
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005062 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005063 Sema::CheckedConversionKind CCK
5064 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5065 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005066 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005067 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005068 ExprResult CurInitExprRes =
5069 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005070 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005071 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005072 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005073 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005074 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Douglas Gregor51e77d52009-12-10 17:56:55 +00005077 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005078 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005079 // Hack: We must pass *ResultType if available in order to set the type
5080 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5081 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5082 // temporary, not a reference, so we should pass Ty.
5083 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5084 // Since this step is never used for a reference directly, we explicitly
5085 // unwrap references here and rewrap them afterwards.
5086 // We also need to create a InitializeTemporary entity for this.
5087 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5088 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5089 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5090 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5091 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005092 Kind.getKind() != InitializationKind::IK_Direct ||
5093 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005094 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005095 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005096
Sebastian Redl29526f02011-11-27 16:50:07 +00005097 if (ResultType) {
5098 if ((*ResultType)->isRValueReferenceType())
5099 Ty = S.Context.getRValueReferenceType(Ty);
5100 else if ((*ResultType)->isLValueReferenceType())
5101 Ty = S.Context.getLValueReferenceType(Ty,
5102 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5103 *ResultType = Ty;
5104 }
5105
5106 InitListExpr *StructuredInitList =
5107 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005108 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005109 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005110 break;
5111 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005112
Sebastian Redled2e5322011-12-22 14:44:04 +00005113 case SK_ListConstructorCall: {
5114 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5115 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5116 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5117 move(Arg), *Step,
5118 ConstructorInitRequiresZeroInit);
5119 break;
5120 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005121
Sebastian Redl29526f02011-11-27 16:50:07 +00005122 case SK_UnwrapInitList:
5123 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5124 break;
5125
5126 case SK_RewrapInitList: {
5127 Expr *E = CurInit.take();
5128 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5129 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5130 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5131 ILE->setSyntacticForm(Syntactic);
5132 ILE->setType(E->getType());
5133 ILE->setValueKind(E->getValueKind());
5134 CurInit = S.Owned(ILE);
5135 break;
5136 }
5137
Sebastian Redled2e5322011-12-22 14:44:04 +00005138 case SK_ConstructorInitialization:
5139 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5140 *Step,
5141 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005142 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005144 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005145 step_iterator NextStep = Step;
5146 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005148 NextStep->Kind == SK_ConstructorInitialization) {
5149 // The need for zero-initialization is recorded directly into
5150 // the call to the object's constructor within the next step.
5151 ConstructorInitRequiresZeroInit = true;
5152 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5153 S.getLangOptions().CPlusPlus &&
5154 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005155 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5156 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005158 Kind.getRange().getBegin());
5159
5160 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5161 TSInfo->getType().getNonLValueExprType(S.Context),
5162 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005163 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005164 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005165 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005166 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005167 break;
5168 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005169
5170 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005171 QualType SourceType = CurInit.get()->getType();
5172 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005173 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005174 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5175 if (Result.isInvalid())
5176 return ExprError();
5177 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005178
5179 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005180 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005181 if (ConvTy != Sema::Compatible &&
5182 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005183 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005184 == Sema::Compatible)
5185 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005186 if (CurInitExprRes.isInvalid())
5187 return ExprError();
5188 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005189
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005190 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005191 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5192 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005193 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005194 getAssignmentAction(Entity),
5195 &Complained)) {
5196 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005197 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005198 } else if (Complained)
5199 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005200 break;
5201 }
Eli Friedman78275202009-12-19 08:11:05 +00005202
5203 case SK_StringInit: {
5204 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005205 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005206 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005207 break;
5208 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005209
5210 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005211 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005212 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005213 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005214 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005215
5216 case SK_ArrayInit:
5217 // Okay: we checked everything before creating this step. Note that
5218 // this is a GNU extension.
5219 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005220 << Step->Type << CurInit.get()->getType()
5221 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005222
5223 // If the destination type is an incomplete array type, update the
5224 // type accordingly.
5225 if (ResultType) {
5226 if (const IncompleteArrayType *IncompleteDest
5227 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5228 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005229 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005230 *ResultType = S.Context.getConstantArrayType(
5231 IncompleteDest->getElementType(),
5232 ConstantSource->getSize(),
5233 ArrayType::Normal, 0);
5234 }
5235 }
5236 }
John McCall31168b02011-06-15 23:02:42 +00005237 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005238
John McCall31168b02011-06-15 23:02:42 +00005239 case SK_PassByIndirectCopyRestore:
5240 case SK_PassByIndirectRestore:
5241 checkIndirectCopyRestoreSource(S, CurInit.get());
5242 CurInit = S.Owned(new (S.Context)
5243 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5244 Step->Kind == SK_PassByIndirectCopyRestore));
5245 break;
5246
5247 case SK_ProduceObjCObject:
5248 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005249 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005250 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005251 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005252 }
5253 }
John McCall1f425642010-11-11 03:21:53 +00005254
5255 // Diagnose non-fatal problems with the completed initialization.
5256 if (Entity.getKind() == InitializedEntity::EK_Member &&
5257 cast<FieldDecl>(Entity.getDecl())->isBitField())
5258 S.CheckBitFieldInitialization(Kind.getLocation(),
5259 cast<FieldDecl>(Entity.getDecl()),
5260 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005261
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005262 return move(CurInit);
5263}
5264
5265//===----------------------------------------------------------------------===//
5266// Diagnose initialization failures
5267//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005268bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005269 const InitializedEntity &Entity,
5270 const InitializationKind &Kind,
5271 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005272 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274
Douglas Gregor1b303932009-12-22 15:35:07 +00005275 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005276 switch (Failure) {
5277 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005278 // FIXME: Customize for the initialized entity?
5279 if (NumArgs == 0)
5280 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5281 << DestType.getNonReferenceType();
5282 else // FIXME: diagnostic below could be better!
5283 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5284 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005285 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005286
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005287 case FK_ArrayNeedsInitList:
5288 case FK_ArrayNeedsInitListOrStringLiteral:
5289 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5290 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5291 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005292
Douglas Gregore2f943b2011-02-22 18:29:51 +00005293 case FK_ArrayTypeMismatch:
5294 case FK_NonConstantArrayInit:
5295 S.Diag(Kind.getLocation(),
5296 (Failure == FK_ArrayTypeMismatch
5297 ? diag::err_array_init_different_type
5298 : diag::err_array_init_non_constant_array))
5299 << DestType.getNonReferenceType()
5300 << Args[0]->getType()
5301 << Args[0]->getSourceRange();
5302 break;
5303
John McCalla59dc2f2012-01-05 00:13:19 +00005304 case FK_VariableLengthArrayHasInitializer:
5305 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5306 << Args[0]->getSourceRange();
5307 break;
5308
John McCall16df1e52010-03-30 21:47:33 +00005309 case FK_AddressOfOverloadFailed: {
5310 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005313 true,
5314 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005315 break;
John McCall16df1e52010-03-30 21:47:33 +00005316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005317
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005318 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005319 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005320 switch (FailedOverloadResult) {
5321 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005322 if (Failure == FK_UserConversionOverloadFailed)
5323 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5324 << Args[0]->getType() << DestType
5325 << Args[0]->getSourceRange();
5326 else
5327 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5328 << DestType << Args[0]->getType()
5329 << Args[0]->getSourceRange();
5330
John McCall5c32be02010-08-24 20:38:10 +00005331 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005332 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005333
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005334 case OR_No_Viable_Function:
5335 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5336 << Args[0]->getType() << DestType.getNonReferenceType()
5337 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005338 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005339 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005341 case OR_Deleted: {
5342 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5343 << Args[0]->getType() << DestType.getNonReferenceType()
5344 << Args[0]->getSourceRange();
5345 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005346 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005347 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5348 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005349 if (Ovl == OR_Deleted) {
5350 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005351 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005352 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005353 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005354 }
5355 break;
5356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005358 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005359 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005360 break;
5361 }
5362 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005364 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005365 if (isa<InitListExpr>(Args[0])) {
5366 S.Diag(Kind.getLocation(),
5367 diag::err_lvalue_reference_bind_to_initlist)
5368 << DestType.getNonReferenceType().isVolatileQualified()
5369 << DestType.getNonReferenceType()
5370 << Args[0]->getSourceRange();
5371 break;
5372 }
5373 // Intentional fallthrough
5374
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005375 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005376 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005377 Failure == FK_NonConstLValueReferenceBindingToTemporary
5378 ? diag::err_lvalue_reference_bind_to_temporary
5379 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005380 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005381 << DestType.getNonReferenceType()
5382 << Args[0]->getType()
5383 << Args[0]->getSourceRange();
5384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005386 case FK_RValueReferenceBindingToLValue:
5387 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005388 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005389 << Args[0]->getSourceRange();
5390 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005392 case FK_ReferenceInitDropsQualifiers:
5393 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5394 << DestType.getNonReferenceType()
5395 << Args[0]->getType()
5396 << Args[0]->getSourceRange();
5397 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005399 case FK_ReferenceInitFailed:
5400 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5401 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005402 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005403 << Args[0]->getType()
5404 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005405 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5406 Args[0]->getType()->isObjCObjectPointerType())
5407 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409
Douglas Gregorb491ed32011-02-19 21:32:49 +00005410 case FK_ConversionFailed: {
5411 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005412 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005413 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005414 << DestType
John McCall086a4642010-11-24 05:12:34 +00005415 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005416 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005417 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005418 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5419 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005420 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5421 Args[0]->getType()->isObjCObjectPointerType())
5422 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005423 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005424 }
John Wiegley01296292011-04-08 18:41:53 +00005425
5426 case FK_ConversionFromPropertyFailed:
5427 // No-op. This error has already been reported.
5428 break;
5429
Douglas Gregor51e77d52009-12-10 17:56:55 +00005430 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005431 SourceRange R;
5432
5433 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005434 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005435 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005437 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005438
Douglas Gregor8ec51732010-09-08 21:40:08 +00005439 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5440 if (Kind.isCStyleOrFunctionalCast())
5441 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5442 << R;
5443 else
5444 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5445 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005446 break;
5447 }
5448
5449 case FK_ReferenceBindingToInitList:
5450 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5451 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5452 break;
5453
5454 case FK_InitListBadDestinationType:
5455 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5456 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5457 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005459 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005460 case FK_ConstructorOverloadFailed: {
5461 SourceRange ArgsRange;
5462 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005464 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005465
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005466 if (Failure == FK_ListConstructorOverloadFailed) {
5467 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5468 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5469 Args = InitList->getInits();
5470 NumArgs = InitList->getNumInits();
5471 }
5472
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005473 // FIXME: Using "DestType" for the entity we're printing is probably
5474 // bad.
5475 switch (FailedOverloadResult) {
5476 case OR_Ambiguous:
5477 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5478 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005479 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5480 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005481 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005482
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005483 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005484 if (Kind.getKind() == InitializationKind::IK_Default &&
5485 (Entity.getKind() == InitializedEntity::EK_Base ||
5486 Entity.getKind() == InitializedEntity::EK_Member) &&
5487 isa<CXXConstructorDecl>(S.CurContext)) {
5488 // This is implicit default initialization of a member or
5489 // base within a constructor. If no viable function was
5490 // found, notify the user that she needs to explicitly
5491 // initialize this base/member.
5492 CXXConstructorDecl *Constructor
5493 = cast<CXXConstructorDecl>(S.CurContext);
5494 if (Entity.getKind() == InitializedEntity::EK_Base) {
5495 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5496 << Constructor->isImplicit()
5497 << S.Context.getTypeDeclType(Constructor->getParent())
5498 << /*base=*/0
5499 << Entity.getType();
5500
5501 RecordDecl *BaseDecl
5502 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5503 ->getDecl();
5504 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5505 << S.Context.getTagDeclType(BaseDecl);
5506 } else {
5507 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5508 << Constructor->isImplicit()
5509 << S.Context.getTypeDeclType(Constructor->getParent())
5510 << /*member=*/1
5511 << Entity.getName();
5512 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5513
5514 if (const RecordType *Record
5515 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005516 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005517 diag::note_previous_decl)
5518 << S.Context.getTagDeclType(Record->getDecl());
5519 }
5520 break;
5521 }
5522
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005523 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5524 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005525 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005526 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005528 case OR_Deleted: {
5529 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5530 << true << DestType << ArgsRange;
5531 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005532 OverloadingResult Ovl
5533 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005534 if (Ovl == OR_Deleted) {
5535 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005536 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005537 } else {
5538 llvm_unreachable("Inconsistent overload resolution?");
5539 }
5540 break;
5541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005542
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005543 case OR_Success:
5544 llvm_unreachable("Conversion did not fail!");
5545 break;
5546 }
5547 break;
5548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549
Douglas Gregor85dabae2009-12-16 01:38:02 +00005550 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005551 if (Entity.getKind() == InitializedEntity::EK_Member &&
5552 isa<CXXConstructorDecl>(S.CurContext)) {
5553 // This is implicit default-initialization of a const member in
5554 // a constructor. Complain that it needs to be explicitly
5555 // initialized.
5556 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5557 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5558 << Constructor->isImplicit()
5559 << S.Context.getTypeDeclType(Constructor->getParent())
5560 << /*const=*/1
5561 << Entity.getName();
5562 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5563 << Entity.getName();
5564 } else {
5565 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5566 << DestType << (bool)DestType->getAs<RecordType>();
5567 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005570 case FK_Incomplete:
5571 S.RequireCompleteType(Kind.getLocation(), DestType,
5572 diag::err_init_incomplete_type);
5573 break;
5574
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005575 case FK_ListInitializationFailed: {
5576 // Run the init list checker again to emit diagnostics.
5577 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5578 QualType DestType = Entity.getType();
5579 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005580 DestType, /*VerifyOnly=*/false,
5581 Kind.getKind() != InitializationKind::IK_Direct ||
5582 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005583 assert(DiagnoseInitList.HadError() &&
5584 "Inconsistent init list check result.");
5585 break;
5586 }
John McCall4124c492011-10-17 18:40:02 +00005587
5588 case FK_PlaceholderType: {
5589 // FIXME: Already diagnosed!
5590 break;
5591 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005594 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005595 return true;
5596}
Douglas Gregore1314a62009-12-18 05:02:21 +00005597
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005598void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005599 switch (SequenceKind) {
5600 case FailedSequence: {
5601 OS << "Failed sequence: ";
5602 switch (Failure) {
5603 case FK_TooManyInitsForReference:
5604 OS << "too many initializers for reference";
5605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005606
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005607 case FK_ArrayNeedsInitList:
5608 OS << "array requires initializer list";
5609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005611 case FK_ArrayNeedsInitListOrStringLiteral:
5612 OS << "array requires initializer list or string literal";
5613 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005614
Douglas Gregore2f943b2011-02-22 18:29:51 +00005615 case FK_ArrayTypeMismatch:
5616 OS << "array type mismatch";
5617 break;
5618
5619 case FK_NonConstantArrayInit:
5620 OS << "non-constant array initializer";
5621 break;
5622
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005623 case FK_AddressOfOverloadFailed:
5624 OS << "address of overloaded function failed";
5625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005627 case FK_ReferenceInitOverloadFailed:
5628 OS << "overload resolution for reference initialization failed";
5629 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005630
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005631 case FK_NonConstLValueReferenceBindingToTemporary:
5632 OS << "non-const lvalue reference bound to temporary";
5633 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005635 case FK_NonConstLValueReferenceBindingToUnrelated:
5636 OS << "non-const lvalue reference bound to unrelated type";
5637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005638
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005639 case FK_RValueReferenceBindingToLValue:
5640 OS << "rvalue reference bound to an lvalue";
5641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005642
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005643 case FK_ReferenceInitDropsQualifiers:
5644 OS << "reference initialization drops qualifiers";
5645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005647 case FK_ReferenceInitFailed:
5648 OS << "reference initialization failed";
5649 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005651 case FK_ConversionFailed:
5652 OS << "conversion failed";
5653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654
John Wiegley01296292011-04-08 18:41:53 +00005655 case FK_ConversionFromPropertyFailed:
5656 OS << "conversion from property failed";
5657 break;
5658
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005659 case FK_TooManyInitsForScalar:
5660 OS << "too many initializers for scalar";
5661 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005663 case FK_ReferenceBindingToInitList:
5664 OS << "referencing binding to initializer list";
5665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005666
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005667 case FK_InitListBadDestinationType:
5668 OS << "initializer list for non-aggregate, non-scalar type";
5669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005671 case FK_UserConversionOverloadFailed:
5672 OS << "overloading failed for user-defined conversion";
5673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005675 case FK_ConstructorOverloadFailed:
5676 OS << "constructor overloading failed";
5677 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005679 case FK_DefaultInitOfConst:
5680 OS << "default initialization of a const variable";
5681 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005683 case FK_Incomplete:
5684 OS << "initialization of incomplete type";
5685 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005686
5687 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005688 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005689 break;
5690
John McCalla59dc2f2012-01-05 00:13:19 +00005691 case FK_VariableLengthArrayHasInitializer:
5692 OS << "variable length array has an initializer";
5693 break;
5694
John McCall4124c492011-10-17 18:40:02 +00005695 case FK_PlaceholderType:
5696 OS << "initializer expression isn't contextually valid";
5697 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005698
5699 case FK_ListConstructorOverloadFailed:
5700 OS << "list constructor overloading failed";
5701 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005703 OS << '\n';
5704 return;
5705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005707 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005708 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005709 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710
Sebastian Redld201edf2011-06-05 13:59:11 +00005711 case NormalSequence:
5712 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005713 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005715
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005716 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5717 if (S != step_begin()) {
5718 OS << " -> ";
5719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005721 switch (S->Kind) {
5722 case SK_ResolveAddressOfOverloadedFunction:
5723 OS << "resolve address of overloaded function";
5724 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005726 case SK_CastDerivedToBaseRValue:
5727 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005729
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005730 case SK_CastDerivedToBaseXValue:
5731 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005734 case SK_CastDerivedToBaseLValue:
5735 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005738 case SK_BindReference:
5739 OS << "bind reference to lvalue";
5740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005742 case SK_BindReferenceToTemporary:
5743 OS << "bind reference to a temporary";
5744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005746 case SK_ExtraneousCopyToTemporary:
5747 OS << "extraneous C++03 copy to temporary";
5748 break;
5749
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005750 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005751 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005752 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005753
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005754 case SK_QualificationConversionRValue:
5755 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005756 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005757
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005758 case SK_QualificationConversionXValue:
5759 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005760 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005761
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005762 case SK_QualificationConversionLValue:
5763 OS << "qualification conversion (lvalue)";
5764 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005766 case SK_ConversionSequence:
5767 OS << "implicit conversion sequence (";
5768 S->ICS->DebugPrint(); // FIXME: use OS
5769 OS << ")";
5770 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005771
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005772 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005773 OS << "list aggregate initialization";
5774 break;
5775
5776 case SK_ListConstructorCall:
5777 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005778 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779
Sebastian Redl29526f02011-11-27 16:50:07 +00005780 case SK_UnwrapInitList:
5781 OS << "unwrap reference initializer list";
5782 break;
5783
5784 case SK_RewrapInitList:
5785 OS << "rewrap reference initializer list";
5786 break;
5787
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005788 case SK_ConstructorInitialization:
5789 OS << "constructor initialization";
5790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005792 case SK_ZeroInitialization:
5793 OS << "zero initialization";
5794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005795
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005796 case SK_CAssignment:
5797 OS << "C assignment";
5798 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005800 case SK_StringInit:
5801 OS << "string initialization";
5802 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005803
5804 case SK_ObjCObjectConversion:
5805 OS << "Objective-C object conversion";
5806 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005807
5808 case SK_ArrayInit:
5809 OS << "array initialization";
5810 break;
John McCall31168b02011-06-15 23:02:42 +00005811
5812 case SK_PassByIndirectCopyRestore:
5813 OS << "pass by indirect copy and restore";
5814 break;
5815
5816 case SK_PassByIndirectRestore:
5817 OS << "pass by indirect restore";
5818 break;
5819
5820 case SK_ProduceObjCObject:
5821 OS << "Objective-C object retension";
5822 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005823 }
5824 }
5825}
5826
5827void InitializationSequence::dump() const {
5828 dump(llvm::errs());
5829}
5830
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005831static void DiagnoseNarrowingInInitList(
5832 Sema& S, QualType EntityType, const Expr *InitE,
5833 bool Constant, const APValue &ConstantValue) {
5834 if (Constant) {
5835 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005836 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005837 ? diag::err_init_list_constant_narrowing
5838 : diag::warn_init_list_constant_narrowing)
5839 << InitE->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005840 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005841 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005842 } else
5843 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005844 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005845 ? diag::err_init_list_variable_narrowing
5846 : diag::warn_init_list_variable_narrowing)
5847 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005848 << InitE->getType().getLocalUnqualifiedType()
5849 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005850
5851 llvm::SmallString<128> StaticCast;
5852 llvm::raw_svector_ostream OS(StaticCast);
5853 OS << "static_cast<";
5854 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5855 // It's important to use the typedef's name if there is one so that the
5856 // fixit doesn't break code using types like int64_t.
5857 //
5858 // FIXME: This will break if the typedef requires qualification. But
5859 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005860 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005861 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5862 OS << BT->getName(S.getLangOptions());
5863 else {
5864 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5865 // with a broken cast.
5866 return;
5867 }
5868 OS << ">(";
5869 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5870 << InitE->getSourceRange()
5871 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5872 << FixItHint::CreateInsertion(
5873 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5874}
5875
Douglas Gregore1314a62009-12-18 05:02:21 +00005876//===----------------------------------------------------------------------===//
5877// Initialization helper functions
5878//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005879bool
5880Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5881 ExprResult Init) {
5882 if (Init.isInvalid())
5883 return false;
5884
5885 Expr *InitE = Init.get();
5886 assert(InitE && "No initialization expression");
5887
5888 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5889 SourceLocation());
5890 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005891 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005892}
5893
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005894ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005895Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5896 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005897 ExprResult Init,
5898 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005899 if (Init.isInvalid())
5900 return ExprError();
5901
John McCall1f425642010-11-11 03:21:53 +00005902 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005903 assert(InitE && "No initialization expression?");
5904
5905 if (EqualLoc.isInvalid())
5906 EqualLoc = InitE->getLocStart();
5907
5908 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5909 EqualLoc);
5910 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5911 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005912
5913 bool Constant = false;
5914 APValue Result;
5915 if (TopLevelOfInitList &&
5916 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5917 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5918 Constant, Result);
5919 }
John McCallfaf5fb42010-08-26 23:41:50 +00005920 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005921}