blob: b6033a58f37cd5faf3b555565dc40f4b07a37f50 [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
David Blaikie8a40f702012-01-17 06:56:22 +00002330 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002331}
2332
Douglas Gregora4b592a2009-12-19 03:01:41 +00002333DeclaratorDecl *InitializedEntity::getDecl() const {
2334 switch (getKind()) {
2335 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002336 case EK_Member:
2337 return VariableOrMember;
2338
John McCall31168b02011-06-15 23:02:42 +00002339 case EK_Parameter:
2340 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2341
Douglas Gregora4b592a2009-12-19 03:01:41 +00002342 case EK_Result:
2343 case EK_Exception:
2344 case EK_New:
2345 case EK_Temporary:
2346 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002347 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002348 case EK_ArrayElement:
2349 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002350 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002351 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002352 return 0;
2353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002354
David Blaikie8a40f702012-01-17 06:56:22 +00002355 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002356}
2357
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002358bool InitializedEntity::allowsNRVO() const {
2359 switch (getKind()) {
2360 case EK_Result:
2361 case EK_Exception:
2362 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002364 case EK_Variable:
2365 case EK_Parameter:
2366 case EK_Member:
2367 case EK_New:
2368 case EK_Temporary:
2369 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002370 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002371 case EK_ArrayElement:
2372 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002373 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002374 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002375 break;
2376 }
2377
2378 return false;
2379}
2380
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002381//===----------------------------------------------------------------------===//
2382// Initialization sequence
2383//===----------------------------------------------------------------------===//
2384
2385void InitializationSequence::Step::Destroy() {
2386 switch (Kind) {
2387 case SK_ResolveAddressOfOverloadedFunction:
2388 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002389 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002390 case SK_CastDerivedToBaseLValue:
2391 case SK_BindReference:
2392 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002393 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002394 case SK_UserConversion:
2395 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002396 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002398 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002399 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002400 case SK_UnwrapInitList:
2401 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002402 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002403 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002404 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002405 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002406 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002407 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002408 case SK_PassByIndirectCopyRestore:
2409 case SK_PassByIndirectRestore:
2410 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002411 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002412
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002413 case SK_ConversionSequence:
2414 delete ICS;
2415 }
2416}
2417
Douglas Gregor838fcc32010-03-26 20:14:36 +00002418bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002419 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002420}
2421
2422bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002423 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002424 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425
Douglas Gregor838fcc32010-03-26 20:14:36 +00002426 switch (getFailureKind()) {
2427 case FK_TooManyInitsForReference:
2428 case FK_ArrayNeedsInitList:
2429 case FK_ArrayNeedsInitListOrStringLiteral:
2430 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2431 case FK_NonConstLValueReferenceBindingToTemporary:
2432 case FK_NonConstLValueReferenceBindingToUnrelated:
2433 case FK_RValueReferenceBindingToLValue:
2434 case FK_ReferenceInitDropsQualifiers:
2435 case FK_ReferenceInitFailed:
2436 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002437 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002438 case FK_TooManyInitsForScalar:
2439 case FK_ReferenceBindingToInitList:
2440 case FK_InitListBadDestinationType:
2441 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002442 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002443 case FK_ArrayTypeMismatch:
2444 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002445 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002446 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002447 case FK_PlaceholderType:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002448 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449
Douglas Gregor838fcc32010-03-26 20:14:36 +00002450 case FK_ReferenceInitOverloadFailed:
2451 case FK_UserConversionOverloadFailed:
2452 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002453 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002454 return FailedOverloadResult == OR_Ambiguous;
2455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002456
David Blaikie8a40f702012-01-17 06:56:22 +00002457 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002458}
2459
Douglas Gregorb33eed02010-04-16 22:09:46 +00002460bool InitializationSequence::isConstructorInitialization() const {
2461 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2462}
2463
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002464bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2465 const Expr *Initializer,
2466 bool *isInitializerConstant,
2467 APValue *ConstantValue) const {
2468 if (Steps.empty() || Initializer->isValueDependent())
2469 return false;
2470
2471 const Step &LastStep = Steps.back();
2472 if (LastStep.Kind != SK_ConversionSequence)
2473 return false;
2474
2475 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2476 const StandardConversionSequence *SCS = NULL;
2477 switch (ICS.getKind()) {
2478 case ImplicitConversionSequence::StandardConversion:
2479 SCS = &ICS.Standard;
2480 break;
2481 case ImplicitConversionSequence::UserDefinedConversion:
2482 SCS = &ICS.UserDefined.After;
2483 break;
2484 case ImplicitConversionSequence::AmbiguousConversion:
2485 case ImplicitConversionSequence::EllipsisConversion:
2486 case ImplicitConversionSequence::BadConversion:
2487 return false;
2488 }
2489
2490 // Check if SCS represents a narrowing conversion, according to C++0x
2491 // [dcl.init.list]p7:
2492 //
2493 // A narrowing conversion is an implicit conversion ...
2494 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2495 QualType FromType = SCS->getToType(0);
2496 QualType ToType = SCS->getToType(1);
2497 switch (PossibleNarrowing) {
2498 // * from a floating-point type to an integer type, or
2499 //
2500 // * from an integer type or unscoped enumeration type to a floating-point
2501 // type, except where the source is a constant expression and the actual
2502 // value after conversion will fit into the target type and will produce
2503 // the original value when converted back to the original type, or
2504 case ICK_Floating_Integral:
2505 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2506 *isInitializerConstant = false;
2507 return true;
2508 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2509 llvm::APSInt IntConstantValue;
2510 if (Initializer &&
2511 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2512 // Convert the integer to the floating type.
2513 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2514 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2515 llvm::APFloat::rmNearestTiesToEven);
2516 // And back.
2517 llvm::APSInt ConvertedValue = IntConstantValue;
2518 bool ignored;
2519 Result.convertToInteger(ConvertedValue,
2520 llvm::APFloat::rmTowardZero, &ignored);
2521 // If the resulting value is different, this was a narrowing conversion.
2522 if (IntConstantValue != ConvertedValue) {
2523 *isInitializerConstant = true;
2524 *ConstantValue = APValue(IntConstantValue);
2525 return true;
2526 }
2527 } else {
2528 // Variables are always narrowings.
2529 *isInitializerConstant = false;
2530 return true;
2531 }
2532 }
2533 return false;
2534
2535 // * from long double to double or float, or from double to float, except
2536 // where the source is a constant expression and the actual value after
2537 // conversion is within the range of values that can be represented (even
2538 // if it cannot be represented exactly), or
2539 case ICK_Floating_Conversion:
2540 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2541 // FromType is larger than ToType.
2542 Expr::EvalResult InitializerValue;
2543 // FIXME: Check whether Initializer is a constant expression according
2544 // to C++0x [expr.const], rather than just whether it can be folded.
Richard Smith7b553f12011-10-29 00:50:52 +00002545 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) &&
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002546 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2547 // Constant! (Except for FIXME above.)
2548 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2549 // Convert the source value into the target type.
2550 bool ignored;
2551 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2552 Ctx.getFloatTypeSemantics(ToType),
2553 llvm::APFloat::rmNearestTiesToEven, &ignored);
2554 // If there was no overflow, the source value is within the range of
2555 // values that can be represented.
2556 if (ConvertStatus & llvm::APFloat::opOverflow) {
2557 *isInitializerConstant = true;
2558 *ConstantValue = InitializerValue.Val;
2559 return true;
2560 }
2561 } else {
2562 *isInitializerConstant = false;
2563 return true;
2564 }
2565 }
2566 return false;
2567
2568 // * from an integer type or unscoped enumeration type to an integer type
2569 // that cannot represent all the values of the original type, except where
2570 // the source is a constant expression and the actual value after
2571 // conversion will fit into the target type and will produce the original
2572 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002573 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002574 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2575 // Boolean conversions can be from pointers and pointers to members
2576 // [conv.bool], and those aren't considered narrowing conversions.
2577 return false;
2578 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002579 case ICK_Integral_Conversion: {
2580 assert(FromType->isIntegralOrUnscopedEnumerationType());
2581 assert(ToType->isIntegralOrUnscopedEnumerationType());
2582 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2583 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2584 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2585 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2586
2587 if (FromWidth > ToWidth ||
2588 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2589 // Not all values of FromType can be represented in ToType.
2590 llvm::APSInt InitializerValue;
2591 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2592 *isInitializerConstant = true;
2593 *ConstantValue = APValue(InitializerValue);
2594
2595 // Add a bit to the InitializerValue so we don't have to worry about
2596 // signed vs. unsigned comparisons.
2597 InitializerValue = InitializerValue.extend(
2598 InitializerValue.getBitWidth() + 1);
2599 // Convert the initializer to and from the target width and signed-ness.
2600 llvm::APSInt ConvertedValue = InitializerValue;
2601 ConvertedValue = ConvertedValue.trunc(ToWidth);
2602 ConvertedValue.setIsSigned(ToSigned);
2603 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2604 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2605 // If the result is different, this was a narrowing conversion.
2606 return ConvertedValue != InitializerValue;
2607 } else {
2608 // Variables are always narrowings.
2609 *isInitializerConstant = false;
2610 return true;
2611 }
2612 }
2613 return false;
2614 }
2615
2616 default:
2617 // Other kinds of conversions are not narrowings.
2618 return false;
2619 }
2620}
2621
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002622void
2623InitializationSequence
2624::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2625 DeclAccessPair Found,
2626 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 Step S;
2628 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2629 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002630 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002631 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002632 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002633 Steps.push_back(S);
2634}
2635
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002636void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002637 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002638 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002639 switch (VK) {
2640 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2641 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2642 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002643 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002644 S.Type = BaseType;
2645 Steps.push_back(S);
2646}
2647
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002649 bool BindingTemporary) {
2650 Step S;
2651 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2652 S.Type = T;
2653 Steps.push_back(S);
2654}
2655
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002656void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2657 Step S;
2658 S.Kind = SK_ExtraneousCopyToTemporary;
2659 S.Type = T;
2660 Steps.push_back(S);
2661}
2662
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002663void
2664InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2665 DeclAccessPair FoundDecl,
2666 QualType T,
2667 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002668 Step S;
2669 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002670 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002671 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002672 S.Function.Function = Function;
2673 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002674 Steps.push_back(S);
2675}
2676
2677void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002678 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002679 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002680 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002681 switch (VK) {
2682 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002683 S.Kind = SK_QualificationConversionRValue;
2684 break;
John McCall2536c6d2010-08-25 10:28:54 +00002685 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002686 S.Kind = SK_QualificationConversionXValue;
2687 break;
John McCall2536c6d2010-08-25 10:28:54 +00002688 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002689 S.Kind = SK_QualificationConversionLValue;
2690 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002691 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002692 S.Type = Ty;
2693 Steps.push_back(S);
2694}
2695
2696void InitializationSequence::AddConversionSequenceStep(
2697 const ImplicitConversionSequence &ICS,
2698 QualType T) {
2699 Step S;
2700 S.Kind = SK_ConversionSequence;
2701 S.Type = T;
2702 S.ICS = new ImplicitConversionSequence(ICS);
2703 Steps.push_back(S);
2704}
2705
Douglas Gregor51e77d52009-12-10 17:56:55 +00002706void InitializationSequence::AddListInitializationStep(QualType T) {
2707 Step S;
2708 S.Kind = SK_ListInitialization;
2709 S.Type = T;
2710 Steps.push_back(S);
2711}
2712
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002714InitializationSequence
2715::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2716 AccessSpecifier Access,
2717 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002718 bool HadMultipleCandidates,
2719 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002720 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002721 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002722 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002723 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002724 S.Function.Function = Constructor;
2725 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002726 Steps.push_back(S);
2727}
2728
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002729void InitializationSequence::AddZeroInitializationStep(QualType T) {
2730 Step S;
2731 S.Kind = SK_ZeroInitialization;
2732 S.Type = T;
2733 Steps.push_back(S);
2734}
2735
Douglas Gregore1314a62009-12-18 05:02:21 +00002736void InitializationSequence::AddCAssignmentStep(QualType T) {
2737 Step S;
2738 S.Kind = SK_CAssignment;
2739 S.Type = T;
2740 Steps.push_back(S);
2741}
2742
Eli Friedman78275202009-12-19 08:11:05 +00002743void InitializationSequence::AddStringInitStep(QualType T) {
2744 Step S;
2745 S.Kind = SK_StringInit;
2746 S.Type = T;
2747 Steps.push_back(S);
2748}
2749
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002750void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2751 Step S;
2752 S.Kind = SK_ObjCObjectConversion;
2753 S.Type = T;
2754 Steps.push_back(S);
2755}
2756
Douglas Gregore2f943b2011-02-22 18:29:51 +00002757void InitializationSequence::AddArrayInitStep(QualType T) {
2758 Step S;
2759 S.Kind = SK_ArrayInit;
2760 S.Type = T;
2761 Steps.push_back(S);
2762}
2763
John McCall31168b02011-06-15 23:02:42 +00002764void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2765 bool shouldCopy) {
2766 Step s;
2767 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2768 : SK_PassByIndirectRestore);
2769 s.Type = type;
2770 Steps.push_back(s);
2771}
2772
2773void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2774 Step S;
2775 S.Kind = SK_ProduceObjCObject;
2776 S.Type = T;
2777 Steps.push_back(S);
2778}
2779
Sebastian Redl29526f02011-11-27 16:50:07 +00002780void InitializationSequence::RewrapReferenceInitList(QualType T,
2781 InitListExpr *Syntactic) {
2782 assert(Syntactic->getNumInits() == 1 &&
2783 "Can only rewrap trivial init lists.");
2784 Step S;
2785 S.Kind = SK_UnwrapInitList;
2786 S.Type = Syntactic->getInit(0)->getType();
2787 Steps.insert(Steps.begin(), S);
2788
2789 S.Kind = SK_RewrapInitList;
2790 S.Type = T;
2791 S.WrappingSyntacticList = Syntactic;
2792 Steps.push_back(S);
2793}
2794
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002796 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002797 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002798 this->Failure = Failure;
2799 this->FailedOverloadResult = Result;
2800}
2801
2802//===----------------------------------------------------------------------===//
2803// Attempt initialization
2804//===----------------------------------------------------------------------===//
2805
John McCall31168b02011-06-15 23:02:42 +00002806static void MaybeProduceObjCObject(Sema &S,
2807 InitializationSequence &Sequence,
2808 const InitializedEntity &Entity) {
2809 if (!S.getLangOptions().ObjCAutoRefCount) return;
2810
2811 /// When initializing a parameter, produce the value if it's marked
2812 /// __attribute__((ns_consumed)).
2813 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2814 if (!Entity.isParameterConsumed())
2815 return;
2816
2817 assert(Entity.getType()->isObjCRetainableType() &&
2818 "consuming an object of unretainable type?");
2819 Sequence.AddProduceObjCObjectStep(Entity.getType());
2820
2821 /// When initializing a return value, if the return type is a
2822 /// retainable type, then returns need to immediately retain the
2823 /// object. If an autorelease is required, it will be done at the
2824 /// last instant.
2825 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2826 if (!Entity.getType()->isObjCRetainableType())
2827 return;
2828
2829 Sequence.AddProduceObjCObjectStep(Entity.getType());
2830 }
2831}
2832
Sebastian Redled2e5322011-12-22 14:44:04 +00002833/// \brief When initializing from init list via constructor, deal with the
2834/// empty init list and std::initializer_list special cases.
2835///
2836/// \return True if this was a special case, false otherwise.
2837static bool TryListConstructionSpecialCases(Sema &S,
2838 Expr **Args, unsigned NumArgs,
2839 CXXRecordDecl *DestRecordDecl,
2840 QualType DestType,
2841 InitializationSequence &Sequence) {
2842 // C++0x [dcl.init.list]p3:
2843 // List-initialization of an object of type T is defined as follows:
2844 // - If the initializer list has no elements and T is a class type with
2845 // a default constructor, the object is value-initialized.
2846 if (NumArgs == 0) {
2847 if (CXXConstructorDecl *DefaultConstructor =
2848 S.LookupDefaultConstructor(DestRecordDecl)) {
2849 if (DefaultConstructor->isDeleted() ||
2850 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2851 // Fake an overload resolution failure.
2852 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2853 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2854 DefaultConstructor->getAccess());
2855 if (FunctionTemplateDecl *ConstructorTmpl =
2856 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2857 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2858 /*ExplicitArgs*/ 0,
2859 Args, NumArgs, CandidateSet,
2860 /*SuppressUserConversions*/ false);
2861 else
2862 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2863 Args, NumArgs, CandidateSet,
2864 /*SuppressUserConversions*/ false);
2865 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002866 InitializationSequence::FK_ListConstructorOverloadFailed,
2867 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002868 } else
2869 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2870 DefaultConstructor->getAccess(),
2871 DestType,
2872 /*MultipleCandidates=*/false,
2873 /*FromInitList=*/true);
2874 return true;
2875 }
2876 }
2877
2878 // - Otherwise, if T is a specialization of std::initializer_list, [...]
2879 // FIXME: Implement.
2880
2881 // Not a special case.
2882 return false;
2883}
2884
2885/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2886/// enumerates the constructors of the initialized entity and performs overload
2887/// resolution to select the best.
2888/// If FromInitList is true, this is list-initialization of a non-aggregate
2889/// class type.
2890static void TryConstructorInitialization(Sema &S,
2891 const InitializedEntity &Entity,
2892 const InitializationKind &Kind,
2893 Expr **Args, unsigned NumArgs,
2894 QualType DestType,
2895 InitializationSequence &Sequence,
2896 bool FromInitList = false) {
2897 // Check constructor arguments for self reference.
2898 if (DeclaratorDecl *DD = Entity.getDecl())
2899 // Parameters arguments are occassionially constructed with itself,
2900 // for instance, in recursive functions. Skip them.
2901 if (!isa<ParmVarDecl>(DD))
2902 for (unsigned i = 0; i < NumArgs; ++i)
2903 S.CheckSelfReference(DD, Args[i]);
2904
2905 // Build the candidate set directly in the initialization sequence
2906 // structure, so that it will persist if we fail.
2907 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2908 CandidateSet.clear();
2909
2910 // Determine whether we are allowed to call explicit constructors or
2911 // explicit conversion operators.
2912 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2913 Kind.getKind() == InitializationKind::IK_Value ||
2914 Kind.getKind() == InitializationKind::IK_Default);
2915
2916 // The type we're constructing needs to be complete.
2917 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2918 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2919 }
2920
2921 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2922 assert(DestRecordType && "Constructor initialization requires record type");
2923 CXXRecordDecl *DestRecordDecl
2924 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2925
2926 if (FromInitList &&
2927 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2928 DestType, Sequence))
2929 return;
2930
2931 // - Otherwise, if T is a class type, constructors are considered. The
2932 // applicable constructors are enumerated, and the best one is chosen
2933 // through overload resolution.
2934 DeclContext::lookup_iterator Con, ConEnd;
2935 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2936 Con != ConEnd; ++Con) {
2937 NamedDecl *D = *Con;
2938 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2939 bool SuppressUserConversions = false;
2940
2941 // Find the constructor (which may be a template).
2942 CXXConstructorDecl *Constructor = 0;
2943 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2944 if (ConstructorTmpl)
2945 Constructor = cast<CXXConstructorDecl>(
2946 ConstructorTmpl->getTemplatedDecl());
2947 else {
2948 Constructor = cast<CXXConstructorDecl>(D);
2949
2950 // If we're performing copy initialization using a copy constructor, we
2951 // suppress user-defined conversions on the arguments.
2952 // FIXME: Move constructors?
2953 if (Kind.getKind() == InitializationKind::IK_Copy &&
2954 Constructor->isCopyConstructor())
2955 SuppressUserConversions = true;
2956 }
2957
2958 if (!Constructor->isInvalidDecl() &&
2959 (AllowExplicit || !Constructor->isExplicit())) {
2960 if (ConstructorTmpl)
2961 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962 /*ExplicitArgs*/ 0,
2963 Args, NumArgs, CandidateSet,
2964 SuppressUserConversions);
2965 else
2966 S.AddOverloadCandidate(Constructor, FoundDecl,
2967 Args, NumArgs, CandidateSet,
2968 SuppressUserConversions);
2969 }
2970 }
2971
2972 SourceLocation DeclLoc = Kind.getLocation();
2973
2974 // Perform overload resolution. If it fails, return the failed result.
2975 OverloadCandidateSet::iterator Best;
2976 if (OverloadingResult Result
2977 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002978 Sequence.SetOverloadFailure(FromInitList ?
2979 InitializationSequence::FK_ListConstructorOverloadFailed :
2980 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002981 Result);
2982 return;
2983 }
2984
2985 // C++0x [dcl.init]p6:
2986 // If a program calls for the default initialization of an object
2987 // of a const-qualified type T, T shall be a class type with a
2988 // user-provided default constructor.
2989 if (Kind.getKind() == InitializationKind::IK_Default &&
2990 Entity.getType().isConstQualified() &&
2991 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2992 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2993 return;
2994 }
2995
2996 // Add the constructor initialization step. Any cv-qualification conversion is
2997 // subsumed by the initialization.
2998 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2999 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3000 Sequence.AddConstructorInitializationStep(CtorDecl,
3001 Best->FoundDecl.getAccess(),
3002 DestType, HadMultipleCandidates,
3003 FromInitList);
3004}
3005
Sebastian Redl29526f02011-11-27 16:50:07 +00003006static bool
3007ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3008 Expr *Initializer,
3009 QualType &SourceType,
3010 QualType &UnqualifiedSourceType,
3011 QualType UnqualifiedTargetType,
3012 InitializationSequence &Sequence) {
3013 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3014 S.Context.OverloadTy) {
3015 DeclAccessPair Found;
3016 bool HadMultipleCandidates = false;
3017 if (FunctionDecl *Fn
3018 = S.ResolveAddressOfOverloadedFunction(Initializer,
3019 UnqualifiedTargetType,
3020 false, Found,
3021 &HadMultipleCandidates)) {
3022 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3023 HadMultipleCandidates);
3024 SourceType = Fn->getType();
3025 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3026 } else if (!UnqualifiedTargetType->isRecordType()) {
3027 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3028 return true;
3029 }
3030 }
3031 return false;
3032}
3033
3034static void TryReferenceInitializationCore(Sema &S,
3035 const InitializedEntity &Entity,
3036 const InitializationKind &Kind,
3037 Expr *Initializer,
3038 QualType cv1T1, QualType T1,
3039 Qualifiers T1Quals,
3040 QualType cv2T2, QualType T2,
3041 Qualifiers T2Quals,
3042 InitializationSequence &Sequence);
3043
3044static void TryListInitialization(Sema &S,
3045 const InitializedEntity &Entity,
3046 const InitializationKind &Kind,
3047 InitListExpr *InitList,
3048 InitializationSequence &Sequence);
3049
3050/// \brief Attempt list initialization of a reference.
3051static void TryReferenceListInitialization(Sema &S,
3052 const InitializedEntity &Entity,
3053 const InitializationKind &Kind,
3054 InitListExpr *InitList,
3055 InitializationSequence &Sequence)
3056{
3057 // First, catch C++03 where this isn't possible.
3058 if (!S.getLangOptions().CPlusPlus0x) {
3059 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3060 return;
3061 }
3062
3063 QualType DestType = Entity.getType();
3064 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3065 Qualifiers T1Quals;
3066 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3067
3068 // Reference initialization via an initializer list works thus:
3069 // If the initializer list consists of a single element that is
3070 // reference-related to the referenced type, bind directly to that element
3071 // (possibly creating temporaries).
3072 // Otherwise, initialize a temporary with the initializer list and
3073 // bind to that.
3074 if (InitList->getNumInits() == 1) {
3075 Expr *Initializer = InitList->getInit(0);
3076 QualType cv2T2 = Initializer->getType();
3077 Qualifiers T2Quals;
3078 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3079
3080 // If this fails, creating a temporary wouldn't work either.
3081 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3082 T1, Sequence))
3083 return;
3084
3085 SourceLocation DeclLoc = Initializer->getLocStart();
3086 bool dummy1, dummy2, dummy3;
3087 Sema::ReferenceCompareResult RefRelationship
3088 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3089 dummy2, dummy3);
3090 if (RefRelationship >= Sema::Ref_Related) {
3091 // Try to bind the reference here.
3092 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3093 T1Quals, cv2T2, T2, T2Quals, Sequence);
3094 if (Sequence)
3095 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3096 return;
3097 }
3098 }
3099
3100 // Not reference-related. Create a temporary and bind to that.
3101 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3102
3103 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3104 if (Sequence) {
3105 if (DestType->isRValueReferenceType() ||
3106 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3107 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3108 else
3109 Sequence.SetFailed(
3110 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3111 }
3112}
3113
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003114/// \brief Attempt list initialization (C++0x [dcl.init.list])
3115static void TryListInitialization(Sema &S,
3116 const InitializedEntity &Entity,
3117 const InitializationKind &Kind,
3118 InitListExpr *InitList,
3119 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003120 QualType DestType = Entity.getType();
3121
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003122 // C++ doesn't allow scalar initialization with more than one argument.
3123 // But C99 complex numbers are scalars and it makes sense there.
3124 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3125 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3126 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3127 return;
3128 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003129 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003130 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003131 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003132 }
3133 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003134 if (S.getLangOptions().CPlusPlus0x)
3135 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3136 InitList->getNumInits(), DestType, Sequence,
3137 /*FromInitList=*/true);
3138 else
3139 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003140 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003141 }
3142
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003143 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003144 DestType, /*VerifyOnly=*/true,
3145 Kind.getKind() != InitializationKind::IK_Direct ||
3146 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003147 if (CheckInitList.HadError()) {
3148 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3149 return;
3150 }
3151
3152 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003153 Sequence.AddListInitializationStep(DestType);
3154}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003155
3156/// \brief Try a reference initialization that involves calling a conversion
3157/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3159 const InitializedEntity &Entity,
3160 const InitializationKind &Kind,
3161 Expr *Initializer,
3162 bool AllowRValues,
3163 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003164 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003165 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3166 QualType T1 = cv1T1.getUnqualifiedType();
3167 QualType cv2T2 = Initializer->getType();
3168 QualType T2 = cv2T2.getUnqualifiedType();
3169
3170 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003171 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003172 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003174 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003175 ObjCConversion,
3176 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003178 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003179 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003180 (void)ObjCLifetimeConversion;
3181
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003182 // Build the candidate set directly in the initialization sequence
3183 // structure, so that it will persist if we fail.
3184 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3185 CandidateSet.clear();
3186
3187 // Determine whether we are allowed to call explicit constructors or
3188 // explicit conversion operators.
3189 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003190
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003191 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003192 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3193 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003194 // The type we're converting to is a class type. Enumerate its constructors
3195 // to see if there is a suitable conversion.
3196 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003197
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003198 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003199 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003201 NamedDecl *D = *Con;
3202 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3203
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003204 // Find the constructor (which may be a template).
3205 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003206 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003207 if (ConstructorTmpl)
3208 Constructor = cast<CXXConstructorDecl>(
3209 ConstructorTmpl->getTemplatedDecl());
3210 else
John McCalla0296f72010-03-19 07:35:19 +00003211 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003213 if (!Constructor->isInvalidDecl() &&
3214 Constructor->isConvertingConstructor(AllowExplicit)) {
3215 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003216 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003217 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003218 &Initializer, 1, CandidateSet,
3219 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003220 else
John McCalla0296f72010-03-19 07:35:19 +00003221 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003222 &Initializer, 1, CandidateSet,
3223 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 }
John McCall3696dcb2010-08-17 07:23:57 +00003227 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3228 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229
Douglas Gregor496e8b342010-05-07 19:42:26 +00003230 const RecordType *T2RecordType = 0;
3231 if ((T2RecordType = T2->getAs<RecordType>()) &&
3232 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003233 // The type we're converting from is a class type, enumerate its conversion
3234 // functions.
3235 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3236
John McCallad371252010-01-20 00:46:10 +00003237 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003239 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3240 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003241 NamedDecl *D = *I;
3242 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3243 if (isa<UsingShadowDecl>(D))
3244 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003246 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3247 CXXConversionDecl *Conv;
3248 if (ConvTemplate)
3249 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3250 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003251 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003252
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003253 // If the conversion function doesn't return a reference type,
3254 // it can't be considered for this conversion unless we're allowed to
3255 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 // FIXME: Do we need to make sure that we only consider conversion
3257 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003258 // break recursion.
3259 if ((AllowExplicit || !Conv->isExplicit()) &&
3260 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3261 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003262 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003263 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003264 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265 else
John McCalla0296f72010-03-19 07:35:19 +00003266 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003267 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003268 }
3269 }
3270 }
John McCall3696dcb2010-08-17 07:23:57 +00003271 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3272 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 SourceLocation DeclLoc = Initializer->getLocStart();
3275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003277 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003279 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003280 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003282 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003283
Chandler Carruth30141632011-02-25 19:41:05 +00003284 // This is the overload that will actually be used for the initialization, so
3285 // mark it as used.
3286 S.MarkDeclarationReferenced(DeclLoc, Function);
3287
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003288 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003289 if (isa<CXXConversionDecl>(Function))
3290 T2 = Function->getResultType();
3291 else
3292 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003293
3294 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003295 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003296 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003297 T2.getNonLValueExprType(S.Context),
3298 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003299
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003301 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003302 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003303 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003304 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003305 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003306 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003307
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003308 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003309 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003310 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003311 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003313 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003314 NewDerivedToBase, NewObjCConversion,
3315 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003316 if (NewRefRelationship == Sema::Ref_Incompatible) {
3317 // If the type we've converted to is not reference-related to the
3318 // type we're looking for, then there is another conversion step
3319 // we need to perform to produce a temporary of the right type
3320 // that we'll be binding to.
3321 ImplicitConversionSequence ICS;
3322 ICS.setStandard();
3323 ICS.Standard = Best->FinalConversion;
3324 T2 = ICS.Standard.getToType(2);
3325 Sequence.AddConversionSequenceStep(ICS, T2);
3326 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 Sequence.AddDerivedToBaseCastStep(
3328 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003330 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003331 else if (NewObjCConversion)
3332 Sequence.AddObjCObjectConversionStep(
3333 S.Context.getQualifiedType(T1,
3334 T2.getNonReferenceType().getQualifiers()));
3335
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003336 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003337 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003338
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003339 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3340 return OR_Success;
3341}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342
Richard Smithc620f552011-10-19 16:55:56 +00003343static void CheckCXX98CompatAccessibleCopy(Sema &S,
3344 const InitializedEntity &Entity,
3345 Expr *CurInitExpr);
3346
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3348static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003349 const InitializedEntity &Entity,
3350 const InitializationKind &Kind,
3351 Expr *Initializer,
3352 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003353 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003354 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003355 Qualifiers T1Quals;
3356 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003357 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003358 Qualifiers T2Quals;
3359 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003360
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003361 // If the initializer is the address of an overloaded function, try
3362 // to resolve the overloaded function. If all goes well, T2 is the
3363 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003364 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3365 T1, Sequence))
3366 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003367
Sebastian Redl29526f02011-11-27 16:50:07 +00003368 // Delegate everything else to a subfunction.
3369 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3370 T1Quals, cv2T2, T2, T2Quals, Sequence);
3371}
3372
3373/// \brief Reference initialization without resolving overloaded functions.
3374static void TryReferenceInitializationCore(Sema &S,
3375 const InitializedEntity &Entity,
3376 const InitializationKind &Kind,
3377 Expr *Initializer,
3378 QualType cv1T1, QualType T1,
3379 Qualifiers T1Quals,
3380 QualType cv2T2, QualType T2,
3381 Qualifiers T2Quals,
3382 InitializationSequence &Sequence) {
3383 QualType DestType = Entity.getType();
3384 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003385 // Compute some basic properties of the types and the initializer.
3386 bool isLValueRef = DestType->isLValueReferenceType();
3387 bool isRValueRef = !isLValueRef;
3388 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003389 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003390 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003391 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003392 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003393 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003394 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003395
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003396 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003397 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003398 // "cv2 T2" as follows:
3399 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003401 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003402 // Note the analogous bullet points for rvlaue refs to functions. Because
3403 // there are no function rvalues in C++, rvalue refs to functions are treated
3404 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003405 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003406 bool T1Function = T1->isFunctionType();
3407 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003409 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003411 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003413 // reference-compatible with "cv2 T2," or
3414 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003416 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003417 // can occur. However, we do pay attention to whether it is a bit-field
3418 // to decide whether we're actually binding to a temporary created from
3419 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003420 if (DerivedToBase)
3421 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003423 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003424 else if (ObjCConversion)
3425 Sequence.AddObjCObjectConversionStep(
3426 S.Context.getQualifiedType(T1, T2Quals));
3427
Chandler Carruth04bdce62010-01-12 20:32:25 +00003428 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003429 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003430 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003431 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003432 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003433 return;
3434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
3436 // - has a class type (i.e., T2 is a class type), where T1 is not
3437 // reference-related to T2, and can be implicitly converted to an
3438 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3439 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003440 // applicable conversion functions (13.3.1.6) and choosing the best
3441 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003442 // If we have an rvalue ref to function type here, the rhs must be
3443 // an rvalue.
3444 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3445 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003447 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003448 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003449 Sequence);
3450 if (ConvOvlResult == OR_Success)
3451 return;
John McCall0d1da222010-01-12 00:44:57 +00003452 if (ConvOvlResult != OR_No_Viable_Function) {
3453 Sequence.SetOverloadFailure(
3454 InitializationSequence::FK_ReferenceInitOverloadFailed,
3455 ConvOvlResult);
3456 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003457 }
3458 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003459
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003461 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003462 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003463 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003464 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3465 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3466 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467 Sequence.SetOverloadFailure(
3468 InitializationSequence::FK_ReferenceInitOverloadFailed,
3469 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003470 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003471 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003472 ? (RefRelationship == Sema::Ref_Related
3473 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3474 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3475 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003476
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003477 return;
3478 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003479
Douglas Gregor92e460e2011-01-20 16:44:54 +00003480 // - If the initializer expression
3481 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3482 // "cv1 T1" is reference-compatible with "cv2 T2"
3483 // Note: functions are handled below.
3484 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003485 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003487 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003488 (InitCategory.isXValue() ||
3489 (InitCategory.isPRValue() && T2->isRecordType()) ||
3490 (InitCategory.isPRValue() && T2->isArrayType()))) {
3491 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3492 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003493 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3494 // compiler the freedom to perform a copy here or bind to the
3495 // object, while C++0x requires that we bind directly to the
3496 // object. Hence, we always bind to the object without making an
3497 // extra copy. However, in C++03 requires that we check for the
3498 // presence of a suitable copy constructor:
3499 //
3500 // The constructor that would be used to make the copy shall
3501 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003502 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003503 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003504 else if (S.getLangOptions().CPlusPlus0x)
3505 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregor92e460e2011-01-20 16:44:54 +00003508 if (DerivedToBase)
3509 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3510 ValueKind);
3511 else if (ObjCConversion)
3512 Sequence.AddObjCObjectConversionStep(
3513 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Douglas Gregor92e460e2011-01-20 16:44:54 +00003515 if (T1Quals != T2Quals)
3516 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003518 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
3522 // - has a class type (i.e., T2 is a class type), where T1 is not
3523 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003524 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3525 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003526 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003527 if (RefRelationship == Sema::Ref_Incompatible) {
3528 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3529 Kind, Initializer,
3530 /*AllowRValues=*/true,
3531 Sequence);
3532 if (ConvOvlResult)
3533 Sequence.SetOverloadFailure(
3534 InitializationSequence::FK_ReferenceInitOverloadFailed,
3535 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003537 return;
3538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003540 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3541 return;
3542 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003543
3544 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003545 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003548
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 // Determine whether we are allowed to call explicit constructors or
3550 // explicit conversion operators.
3551 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003552
3553 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3554
John McCall31168b02011-06-15 23:02:42 +00003555 ImplicitConversionSequence ICS
3556 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003557 /*SuppressUserConversions*/ false,
3558 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003559 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003560 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3561 /*AllowObjCWritebackConversion=*/false);
3562
3563 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564 // FIXME: Use the conversion function set stored in ICS to turn
3565 // this into an overloading ambiguity diagnostic. However, we need
3566 // to keep that set as an OverloadCandidateSet rather than as some
3567 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003568 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3569 Sequence.SetOverloadFailure(
3570 InitializationSequence::FK_ReferenceInitOverloadFailed,
3571 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003572 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3573 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003574 else
3575 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003576 return;
John McCall31168b02011-06-15 23:02:42 +00003577 } else {
3578 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003579 }
3580
3581 // [...] If T1 is reference-related to T2, cv1 must be the
3582 // same cv-qualification as, or greater cv-qualification
3583 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003584 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3585 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003587 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003588 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3589 return;
3590 }
3591
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003593 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003595 InitCategory.isLValue()) {
3596 Sequence.SetFailed(
3597 InitializationSequence::FK_RValueReferenceBindingToLValue);
3598 return;
3599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003601 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3602 return;
3603}
3604
3605/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606/// (C++ [dcl.init.string], C99 6.7.8).
3607static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003608 const InitializedEntity &Entity,
3609 const InitializationKind &Kind,
3610 Expr *Initializer,
3611 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003612 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003613}
3614
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003615/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003617 const InitializedEntity &Entity,
3618 const InitializationKind &Kind,
3619 InitializationSequence &Sequence) {
3620 // C++ [dcl.init]p5:
3621 //
3622 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003623 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003625 // -- if T is an array type, then each element is value-initialized;
3626 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3627 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003629 if (const RecordType *RT = T->getAs<RecordType>()) {
3630 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3631 // -- if T is a class type (clause 9) with a user-declared
3632 // constructor (12.1), then the default constructor for T is
3633 // called (and the initialization is ill-formed if T has no
3634 // accessible default constructor);
3635 //
3636 // FIXME: we really want to refer to a single subobject of the array,
3637 // but Entity doesn't have a way to capture that (yet).
3638 if (ClassDecl->hasUserDeclaredConstructor())
3639 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003641 // -- if T is a (possibly cv-qualified) non-union class type
3642 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003643 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003644 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003645 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003646 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003647 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003649 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003650 }
3651 }
3652
Douglas Gregor1b303932009-12-22 15:35:07 +00003653 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003654}
3655
Douglas Gregor85dabae2009-12-16 01:38:02 +00003656/// \brief Attempt default initialization (C++ [dcl.init]p6).
3657static void TryDefaultInitialization(Sema &S,
3658 const InitializedEntity &Entity,
3659 const InitializationKind &Kind,
3660 InitializationSequence &Sequence) {
3661 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Douglas Gregor85dabae2009-12-16 01:38:02 +00003663 // C++ [dcl.init]p6:
3664 // To default-initialize an object of type T means:
3665 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003666 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3667
Douglas Gregor85dabae2009-12-16 01:38:02 +00003668 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3669 // constructor for T is called (and the initialization is ill-formed if
3670 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003671 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003672 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3673 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675
Douglas Gregor85dabae2009-12-16 01:38:02 +00003676 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677
Douglas Gregor85dabae2009-12-16 01:38:02 +00003678 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003680 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003681 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003682 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003683 return;
3684 }
3685
3686 // If the destination type has a lifetime property, zero-initialize it.
3687 if (DestType.getQualifiers().hasObjCLifetime()) {
3688 Sequence.AddZeroInitializationStep(Entity.getType());
3689 return;
3690 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003691}
3692
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3694/// which enumerates all conversion functions and performs overload resolution
3695/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003697 const InitializedEntity &Entity,
3698 const InitializationKind &Kind,
3699 Expr *Initializer,
3700 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003701 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003702 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3703 QualType SourceType = Initializer->getType();
3704 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3705 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706
Douglas Gregor540c3b02009-12-14 17:27:33 +00003707 // Build the candidate set directly in the initialization sequence
3708 // structure, so that it will persist if we fail.
3709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3710 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711
Douglas Gregor540c3b02009-12-14 17:27:33 +00003712 // Determine whether we are allowed to call explicit constructors or
3713 // explicit conversion operators.
3714 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Douglas Gregor540c3b02009-12-14 17:27:33 +00003716 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3717 // The type we're converting to is a class type. Enumerate its constructors
3718 // to see if there is a suitable conversion.
3719 CXXRecordDecl *DestRecordDecl
3720 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721
Douglas Gregord9848152010-04-26 14:36:57 +00003722 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003724 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003725 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003726 Con != ConEnd; ++Con) {
3727 NamedDecl *D = *Con;
3728 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Douglas Gregord9848152010-04-26 14:36:57 +00003730 // Find the constructor (which may be a template).
3731 CXXConstructorDecl *Constructor = 0;
3732 FunctionTemplateDecl *ConstructorTmpl
3733 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003734 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003735 Constructor = cast<CXXConstructorDecl>(
3736 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003737 else
Douglas Gregord9848152010-04-26 14:36:57 +00003738 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Douglas Gregord9848152010-04-26 14:36:57 +00003740 if (!Constructor->isInvalidDecl() &&
3741 Constructor->isConvertingConstructor(AllowExplicit)) {
3742 if (ConstructorTmpl)
3743 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3744 /*ExplicitArgs*/ 0,
3745 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003746 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003747 else
3748 S.AddOverloadCandidate(Constructor, FoundDecl,
3749 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003750 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752 }
Douglas Gregord9848152010-04-26 14:36:57 +00003753 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003754 }
Eli Friedman78275202009-12-19 08:11:05 +00003755
3756 SourceLocation DeclLoc = Initializer->getLocStart();
3757
Douglas Gregor540c3b02009-12-14 17:27:33 +00003758 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3759 // The type we're converting from is a class type, enumerate its conversion
3760 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003761
Eli Friedman4afe9a32009-12-20 22:12:03 +00003762 // We can only enumerate the conversion functions for a complete type; if
3763 // the type isn't complete, simply skip this step.
3764 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3765 CXXRecordDecl *SourceRecordDecl
3766 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
John McCallad371252010-01-20 00:46:10 +00003768 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003769 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003770 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003772 I != E; ++I) {
3773 NamedDecl *D = *I;
3774 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3775 if (isa<UsingShadowDecl>(D))
3776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
Eli Friedman4afe9a32009-12-20 22:12:03 +00003778 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3779 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003780 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003781 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003782 else
John McCallda4458e2010-03-31 01:36:47 +00003783 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784
Eli Friedman4afe9a32009-12-20 22:12:03 +00003785 if (AllowExplicit || !Conv->isExplicit()) {
3786 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003787 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003788 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003789 CandidateSet);
3790 else
John McCalla0296f72010-03-19 07:35:19 +00003791 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003792 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003793 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003794 }
3795 }
3796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
3798 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003799 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003800 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003801 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003802 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003804 Result);
3805 return;
3806 }
John McCall0d1da222010-01-12 00:44:57 +00003807
Douglas Gregor540c3b02009-12-14 17:27:33 +00003808 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003809 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003810 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811
Douglas Gregor540c3b02009-12-14 17:27:33 +00003812 if (isa<CXXConstructorDecl>(Function)) {
3813 // Add the user-defined conversion step. Any cv-qualification conversion is
3814 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003815 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3816 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003817 return;
3818 }
3819
3820 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003821 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003822 if (ConvType->getAs<RecordType>()) {
3823 // If we're converting to a class type, there may be an copy if
3824 // the resulting temporary object (possible to create an object of
3825 // a base class type). That copy is not a separate conversion, so
3826 // we just make a note of the actual destination type (possibly a
3827 // base class of the type returned by the conversion function) and
3828 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003829 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3830 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003831 return;
3832 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003833
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003834 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3835 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836
Douglas Gregor5ab11652010-04-17 22:01:05 +00003837 // If the conversion following the call to the conversion function
3838 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003839 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3840 Best->FinalConversion.Third) {
3841 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003842 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003843 ICS.Standard = Best->FinalConversion;
3844 Sequence.AddConversionSequenceStep(ICS, DestType);
3845 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003846}
3847
John McCall31168b02011-06-15 23:02:42 +00003848/// The non-zero enum values here are indexes into diagnostic alternatives.
3849enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3850
3851/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003852static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3853 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003854 // Skip parens.
3855 e = e->IgnoreParens();
3856
3857 // Skip address-of nodes.
3858 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3859 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003860 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003861
3862 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003863 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3864 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003865 case CK_Dependent:
3866 case CK_BitCast:
3867 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003868 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003869 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003870
3871 case CK_ArrayToPointerDecay:
3872 return IIK_nonscalar;
3873
3874 case CK_NullToPointer:
3875 return IIK_okay;
3876
3877 default:
3878 break;
3879 }
3880
3881 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003882 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3883 if (!isAddressOf) return IIK_nonlocal;
3884
3885 VarDecl *var;
3886 if (isa<DeclRefExpr>(e)) {
3887 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3888 if (!var) return IIK_nonlocal;
3889 } else {
3890 var = cast<BlockDeclRefExpr>(e)->getDecl();
3891 }
3892
3893 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003894
3895 // If we have a conditional operator, check both sides.
3896 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003897 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003898 return iik;
3899
John McCall63f84442011-06-27 23:59:58 +00003900 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003901
3902 // These are never scalar.
3903 } else if (isa<ArraySubscriptExpr>(e)) {
3904 return IIK_nonscalar;
3905
3906 // Otherwise, it needs to be a null pointer constant.
3907 } else {
3908 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3909 ? IIK_okay : IIK_nonlocal);
3910 }
3911
3912 return IIK_nonlocal;
3913}
3914
3915/// Check whether the given expression is a valid operand for an
3916/// indirect copy/restore.
3917static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3918 assert(src->isRValue());
3919
John McCall63f84442011-06-27 23:59:58 +00003920 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003921 if (iik == IIK_okay) return;
3922
3923 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3924 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3925 << src->getSourceRange();
3926}
3927
Douglas Gregore2f943b2011-02-22 18:29:51 +00003928/// \brief Determine whether we have compatible array types for the
3929/// purposes of GNU by-copy array initialization.
3930static bool hasCompatibleArrayTypes(ASTContext &Context,
3931 const ArrayType *Dest,
3932 const ArrayType *Source) {
3933 // If the source and destination array types are equivalent, we're
3934 // done.
3935 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3936 return true;
3937
3938 // Make sure that the element types are the same.
3939 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3940 return false;
3941
3942 // The only mismatch we allow is when the destination is an
3943 // incomplete array type and the source is a constant array type.
3944 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3945}
3946
John McCall31168b02011-06-15 23:02:42 +00003947static bool tryObjCWritebackConversion(Sema &S,
3948 InitializationSequence &Sequence,
3949 const InitializedEntity &Entity,
3950 Expr *Initializer) {
3951 bool ArrayDecay = false;
3952 QualType ArgType = Initializer->getType();
3953 QualType ArgPointee;
3954 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3955 ArrayDecay = true;
3956 ArgPointee = ArgArrayType->getElementType();
3957 ArgType = S.Context.getPointerType(ArgPointee);
3958 }
3959
3960 // Handle write-back conversion.
3961 QualType ConvertedArgType;
3962 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3963 ConvertedArgType))
3964 return false;
3965
3966 // We should copy unless we're passing to an argument explicitly
3967 // marked 'out'.
3968 bool ShouldCopy = true;
3969 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3970 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3971
3972 // Do we need an lvalue conversion?
3973 if (ArrayDecay || Initializer->isGLValue()) {
3974 ImplicitConversionSequence ICS;
3975 ICS.setStandard();
3976 ICS.Standard.setAsIdentityConversion();
3977
3978 QualType ResultType;
3979 if (ArrayDecay) {
3980 ICS.Standard.First = ICK_Array_To_Pointer;
3981 ResultType = S.Context.getPointerType(ArgPointee);
3982 } else {
3983 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3984 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3985 }
3986
3987 Sequence.AddConversionSequenceStep(ICS, ResultType);
3988 }
3989
3990 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3991 return true;
3992}
3993
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003994InitializationSequence::InitializationSequence(Sema &S,
3995 const InitializedEntity &Entity,
3996 const InitializationKind &Kind,
3997 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003998 unsigned NumArgs)
3999 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004000 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004002 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003 // The semantics of initializers are as follows. The destination type is
4004 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004005 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004007 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004008 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004009
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004010 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004011 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
4012 SequenceKind = DependentSequence;
4013 return;
4014 }
4015
Sebastian Redld201edf2011-06-05 13:59:11 +00004016 // Almost everything is a normal sequence.
4017 setSequenceKind(NormalSequence);
4018
John McCalled75c092010-12-07 22:54:16 +00004019 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00004020 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00004021 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00004022 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4023 if (result.isInvalid()) {
4024 SetFailed(FK_PlaceholderType);
4025 return;
John McCall4124c492011-10-17 18:40:02 +00004026 }
John McCalld5c98ae2011-11-15 01:35:18 +00004027 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00004028 }
John McCalled75c092010-12-07 22:54:16 +00004029
John McCall4124c492011-10-17 18:40:02 +00004030
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004031 QualType SourceType;
4032 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004033 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 Initializer = Args[0];
4035 if (!isa<InitListExpr>(Initializer))
4036 SourceType = Initializer->getType();
4037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004038
4039 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004040 // list-initialized (8.5.4).
4041 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004042 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004043 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046 // - If the destination type is a reference type, see 8.5.3.
4047 if (DestType->isReferenceType()) {
4048 // C++0x [dcl.init.ref]p1:
4049 // A variable declared to be a T& or T&&, that is, "reference to type T"
4050 // (8.3.2), shall be initialized by an object, or function, of type T or
4051 // by an object that can be converted into a T.
4052 // (Therefore, multiple arguments are not permitted.)
4053 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004054 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004055 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004056 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 return;
4058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004060 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004061 if (Kind.getKind() == InitializationKind::IK_Value ||
4062 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004063 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064 return;
4065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Douglas Gregor85dabae2009-12-16 01:38:02 +00004067 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004068 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004069 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004070 return;
4071 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004072
John McCall66884dd2011-02-21 07:22:22 +00004073 // - If the destination type is an array of characters, an array of
4074 // char16_t, an array of char32_t, or an array of wchar_t, and the
4075 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004077 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004078 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004079 if (Initializer && isa<VariableArrayType>(DestAT)) {
4080 SetFailed(FK_VariableLengthArrayHasInitializer);
4081 return;
4082 }
4083
Douglas Gregore2f943b2011-02-22 18:29:51 +00004084 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004085 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004086 return;
4087 }
4088
Douglas Gregore2f943b2011-02-22 18:29:51 +00004089 // Note: as an GNU C extension, we allow initialization of an
4090 // array from a compound literal that creates an array of the same
4091 // type, so long as the initializer has no side effects.
4092 if (!S.getLangOptions().CPlusPlus && Initializer &&
4093 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4094 Initializer->getType()->isArrayType()) {
4095 const ArrayType *SourceAT
4096 = Context.getAsArrayType(Initializer->getType());
4097 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004098 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004099 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004100 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004101 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004102 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004103 }
4104 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004105 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004106 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004107 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004109 return;
4110 }
Eli Friedman78275202009-12-19 08:11:05 +00004111
John McCall31168b02011-06-15 23:02:42 +00004112 // Determine whether we should consider writeback conversions for
4113 // Objective-C ARC.
4114 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4115 Entity.getKind() == InitializedEntity::EK_Parameter;
4116
4117 // We're at the end of the line for C: it's either a write-back conversion
4118 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004119 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004120 // If allowed, check whether this is an Objective-C writeback conversion.
4121 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004122 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004123 return;
4124 }
4125
4126 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004127 AddCAssignmentStep(DestType);
4128 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004129 return;
4130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131
John McCall31168b02011-06-15 23:02:42 +00004132 assert(S.getLangOptions().CPlusPlus);
4133
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004134 // - If the destination type is a (possibly cv-qualified) class type:
4135 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136 // - If the initialization is direct-initialization, or if it is
4137 // copy-initialization where the cv-unqualified version of the
4138 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139 // class of the destination, constructors are considered. [...]
4140 if (Kind.getKind() == InitializationKind::IK_Direct ||
4141 (Kind.getKind() == InitializationKind::IK_Copy &&
4142 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4143 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004145 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004147 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004149 // used) to a derived class thereof are enumerated as described in
4150 // 13.3.1.4, and the best one is chosen through overload resolution
4151 // (13.3).
4152 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004153 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004154 return;
4155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156
Douglas Gregor85dabae2009-12-16 01:38:02 +00004157 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004158 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004159 return;
4160 }
4161 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
4163 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004164 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004165 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004166 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4167 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004168 return;
4169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004171 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004172 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004173 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004175 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004176
4177 ImplicitConversionSequence ICS
4178 = S.TryImplicitConversion(Initializer, Entity.getType(),
4179 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004180 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004181 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004182 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4183 allowObjCWritebackConversion);
4184
4185 if (ICS.isStandard() &&
4186 ICS.Standard.Second == ICK_Writeback_Conversion) {
4187 // Objective-C ARC writeback conversion.
4188
4189 // We should copy unless we're passing to an argument explicitly
4190 // marked 'out'.
4191 bool ShouldCopy = true;
4192 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4193 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4194
4195 // If there was an lvalue adjustment, add it as a separate conversion.
4196 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4197 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4198 ImplicitConversionSequence LvalueICS;
4199 LvalueICS.setStandard();
4200 LvalueICS.Standard.setAsIdentityConversion();
4201 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4202 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004203 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004204 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004205
4206 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004207 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004208 DeclAccessPair dap;
4209 if (Initializer->getType() == Context.OverloadTy &&
4210 !S.ResolveAddressOfOverloadedFunction(Initializer
4211 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004212 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004213 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004214 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004215 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004216 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004217
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004218 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004219 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004220}
4221
4222InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004223 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004224 StepEnd = Steps.end();
4225 Step != StepEnd; ++Step)
4226 Step->Destroy();
4227}
4228
4229//===----------------------------------------------------------------------===//
4230// Perform initialization
4231//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004233getAssignmentAction(const InitializedEntity &Entity) {
4234 switch(Entity.getKind()) {
4235 case InitializedEntity::EK_Variable:
4236 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004237 case InitializedEntity::EK_Exception:
4238 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004239 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004240 return Sema::AA_Initializing;
4241
4242 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004244 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4245 return Sema::AA_Sending;
4246
Douglas Gregore1314a62009-12-18 05:02:21 +00004247 return Sema::AA_Passing;
4248
4249 case InitializedEntity::EK_Result:
4250 return Sema::AA_Returning;
4251
Douglas Gregore1314a62009-12-18 05:02:21 +00004252 case InitializedEntity::EK_Temporary:
4253 // FIXME: Can we tell apart casting vs. converting?
4254 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregore1314a62009-12-18 05:02:21 +00004256 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004257 case InitializedEntity::EK_ArrayElement:
4258 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004259 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004260 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004261 return Sema::AA_Initializing;
4262 }
4263
David Blaikie8a40f702012-01-17 06:56:22 +00004264 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004265}
4266
Douglas Gregor95562572010-04-24 23:45:46 +00004267/// \brief Whether we should binding a created object as a temporary when
4268/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004269static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004270 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004271 case InitializedEntity::EK_ArrayElement:
4272 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004273 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004274 case InitializedEntity::EK_New:
4275 case InitializedEntity::EK_Variable:
4276 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004277 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004278 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004279 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004280 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004281 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004282 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283
Douglas Gregore1314a62009-12-18 05:02:21 +00004284 case InitializedEntity::EK_Parameter:
4285 case InitializedEntity::EK_Temporary:
4286 return true;
4287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregore1314a62009-12-18 05:02:21 +00004289 llvm_unreachable("missed an InitializedEntity kind?");
4290}
4291
Douglas Gregor95562572010-04-24 23:45:46 +00004292/// \brief Whether the given entity, when initialized with an object
4293/// created for that initialization, requires destruction.
4294static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4295 switch (Entity.getKind()) {
4296 case InitializedEntity::EK_Member:
4297 case InitializedEntity::EK_Result:
4298 case InitializedEntity::EK_New:
4299 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004300 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004301 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004302 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004303 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004304 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305
Douglas Gregor95562572010-04-24 23:45:46 +00004306 case InitializedEntity::EK_Variable:
4307 case InitializedEntity::EK_Parameter:
4308 case InitializedEntity::EK_Temporary:
4309 case InitializedEntity::EK_ArrayElement:
4310 case InitializedEntity::EK_Exception:
4311 return true;
4312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
4314 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004315}
4316
Richard Smithc620f552011-10-19 16:55:56 +00004317/// \brief Look for copy and move constructors and constructor templates, for
4318/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4319static void LookupCopyAndMoveConstructors(Sema &S,
4320 OverloadCandidateSet &CandidateSet,
4321 CXXRecordDecl *Class,
4322 Expr *CurInitExpr) {
4323 DeclContext::lookup_iterator Con, ConEnd;
4324 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4325 Con != ConEnd; ++Con) {
4326 CXXConstructorDecl *Constructor = 0;
4327
4328 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4329 // Handle copy/moveconstructors, only.
4330 if (!Constructor || Constructor->isInvalidDecl() ||
4331 !Constructor->isCopyOrMoveConstructor() ||
4332 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4333 continue;
4334
4335 DeclAccessPair FoundDecl
4336 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4337 S.AddOverloadCandidate(Constructor, FoundDecl,
4338 &CurInitExpr, 1, CandidateSet);
4339 continue;
4340 }
4341
4342 // Handle constructor templates.
4343 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4344 if (ConstructorTmpl->isInvalidDecl())
4345 continue;
4346
4347 Constructor = cast<CXXConstructorDecl>(
4348 ConstructorTmpl->getTemplatedDecl());
4349 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4350 continue;
4351
4352 // FIXME: Do we need to limit this to copy-constructor-like
4353 // candidates?
4354 DeclAccessPair FoundDecl
4355 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4356 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4357 &CurInitExpr, 1, CandidateSet, true);
4358 }
4359}
4360
4361/// \brief Get the location at which initialization diagnostics should appear.
4362static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4363 Expr *Initializer) {
4364 switch (Entity.getKind()) {
4365 case InitializedEntity::EK_Result:
4366 return Entity.getReturnLoc();
4367
4368 case InitializedEntity::EK_Exception:
4369 return Entity.getThrowLoc();
4370
4371 case InitializedEntity::EK_Variable:
4372 return Entity.getDecl()->getLocation();
4373
4374 case InitializedEntity::EK_ArrayElement:
4375 case InitializedEntity::EK_Member:
4376 case InitializedEntity::EK_Parameter:
4377 case InitializedEntity::EK_Temporary:
4378 case InitializedEntity::EK_New:
4379 case InitializedEntity::EK_Base:
4380 case InitializedEntity::EK_Delegating:
4381 case InitializedEntity::EK_VectorElement:
4382 case InitializedEntity::EK_ComplexElement:
4383 case InitializedEntity::EK_BlockElement:
4384 return Initializer->getLocStart();
4385 }
4386 llvm_unreachable("missed an InitializedEntity kind?");
4387}
4388
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004389/// \brief Make a (potentially elidable) temporary copy of the object
4390/// provided by the given initializer by calling the appropriate copy
4391/// constructor.
4392///
4393/// \param S The Sema object used for type-checking.
4394///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004395/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004396/// the type of the initializer expression or a superclass thereof.
4397///
4398/// \param Enter The entity being initialized.
4399///
4400/// \param CurInit The initializer expression.
4401///
4402/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4403/// is permitted in C++03 (but not C++0x) when binding a reference to
4404/// an rvalue.
4405///
4406/// \returns An expression that copies the initializer expression into
4407/// a temporary object, or an error expression if a copy could not be
4408/// created.
John McCalldadc5752010-08-24 06:29:42 +00004409static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004410 QualType T,
4411 const InitializedEntity &Entity,
4412 ExprResult CurInit,
4413 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004414 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004415 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004417 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004418 Class = cast<CXXRecordDecl>(Record->getDecl());
4419 if (!Class)
4420 return move(CurInit);
4421
Douglas Gregor5d369002011-01-21 18:05:27 +00004422 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004423 // When certain criteria are met, an implementation is allowed to
4424 // omit the copy/move construction of a class object, even if the
4425 // copy/move constructor and/or destructor for the object have
4426 // side effects. [...]
4427 // - when a temporary class object that has not been bound to a
4428 // reference (12.2) would be copied/moved to a class object
4429 // with the same cv-unqualified type, the copy/move operation
4430 // can be omitted by constructing the temporary object
4431 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004433 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004434 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004436 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004437 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004438 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004439
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004441 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4442 return move(CurInit);
4443
Douglas Gregorf282a762011-01-21 19:38:21 +00004444 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004445 // Only consider constructors and constructor templates. Per
4446 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4447 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004448 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004449 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004451 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4452
Douglas Gregore1314a62009-12-18 05:02:21 +00004453 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004454 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004455 case OR_Success:
4456 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Douglas Gregore1314a62009-12-18 05:02:21 +00004458 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004459 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4460 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4461 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004462 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004463 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004464 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004465 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004466 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004467 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregore1314a62009-12-18 05:02:21 +00004469 case OR_Ambiguous:
4470 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004471 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004472 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004473 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004474 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregore1314a62009-12-18 05:02:21 +00004476 case OR_Deleted:
4477 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004478 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004479 << CurInitExpr->getSourceRange();
4480 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004481 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004482 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004483 }
4484
Douglas Gregor5ab11652010-04-17 22:01:05 +00004485 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004486 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004487 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004488
Anders Carlssona01874b2010-04-21 18:47:17 +00004489 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004490 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004491
4492 if (IsExtraneousCopy) {
4493 // If this is a totally extraneous copy for C++03 reference
4494 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004495 // expression. We don't generate an (elided) copy operation here
4496 // because doing so would require us to pass down a flag to avoid
4497 // infinite recursion, where each step adds another extraneous,
4498 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004499
Douglas Gregor30b52772010-04-18 07:57:34 +00004500 // Instantiate the default arguments of any extra parameters in
4501 // the selected copy constructor, as if we were going to create a
4502 // proper call to the copy constructor.
4503 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4504 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4505 if (S.RequireCompleteType(Loc, Parm->getType(),
4506 S.PDiag(diag::err_call_incomplete_argument)))
4507 break;
4508
4509 // Build the default argument expression; we don't actually care
4510 // if this succeeds or not, because this routine will complain
4511 // if there was a problem.
4512 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4513 }
4514
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004515 return S.Owned(CurInitExpr);
4516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Chandler Carruth30141632011-02-25 19:41:05 +00004518 S.MarkDeclarationReferenced(Loc, Constructor);
4519
Douglas Gregor5ab11652010-04-17 22:01:05 +00004520 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004521 // constructor call (we might have derived-to-base conversions, or
4522 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004523 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004524 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004525 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004526
Douglas Gregord0ace022010-04-25 00:55:24 +00004527 // Actually perform the constructor call.
4528 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004529 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004530 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004531 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004532 CXXConstructExpr::CK_Complete,
4533 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534
Douglas Gregord0ace022010-04-25 00:55:24 +00004535 // If we're supposed to bind temporaries, do so.
4536 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4537 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4538 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004539}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004540
Richard Smithc620f552011-10-19 16:55:56 +00004541/// \brief Check whether elidable copy construction for binding a reference to
4542/// a temporary would have succeeded if we were building in C++98 mode, for
4543/// -Wc++98-compat.
4544static void CheckCXX98CompatAccessibleCopy(Sema &S,
4545 const InitializedEntity &Entity,
4546 Expr *CurInitExpr) {
4547 assert(S.getLangOptions().CPlusPlus0x);
4548
4549 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4550 if (!Record)
4551 return;
4552
4553 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4554 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4555 == DiagnosticsEngine::Ignored)
4556 return;
4557
4558 // Find constructors which would have been considered.
4559 OverloadCandidateSet CandidateSet(Loc);
4560 LookupCopyAndMoveConstructors(
4561 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4562
4563 // Perform overload resolution.
4564 OverloadCandidateSet::iterator Best;
4565 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4566
4567 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4568 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4569 << CurInitExpr->getSourceRange();
4570
4571 switch (OR) {
4572 case OR_Success:
4573 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4574 Best->FoundDecl.getAccess(), Diag);
4575 // FIXME: Check default arguments as far as that's possible.
4576 break;
4577
4578 case OR_No_Viable_Function:
4579 S.Diag(Loc, Diag);
4580 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4581 break;
4582
4583 case OR_Ambiguous:
4584 S.Diag(Loc, Diag);
4585 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4586 break;
4587
4588 case OR_Deleted:
4589 S.Diag(Loc, Diag);
4590 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4591 << 1 << Best->Function->isDeleted();
4592 break;
4593 }
4594}
4595
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004596void InitializationSequence::PrintInitLocationNote(Sema &S,
4597 const InitializedEntity &Entity) {
4598 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4599 if (Entity.getDecl()->getLocation().isInvalid())
4600 return;
4601
4602 if (Entity.getDecl()->getDeclName())
4603 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4604 << Entity.getDecl()->getDeclName();
4605 else
4606 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4607 }
4608}
4609
Sebastian Redl112aa822011-07-14 19:07:55 +00004610static bool isReferenceBinding(const InitializationSequence::Step &s) {
4611 return s.Kind == InitializationSequence::SK_BindReference ||
4612 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4613}
4614
Sebastian Redled2e5322011-12-22 14:44:04 +00004615static ExprResult
4616PerformConstructorInitialization(Sema &S,
4617 const InitializedEntity &Entity,
4618 const InitializationKind &Kind,
4619 MultiExprArg Args,
4620 const InitializationSequence::Step& Step,
4621 bool &ConstructorInitRequiresZeroInit) {
4622 unsigned NumArgs = Args.size();
4623 CXXConstructorDecl *Constructor
4624 = cast<CXXConstructorDecl>(Step.Function.Function);
4625 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4626
4627 // Build a call to the selected constructor.
4628 ASTOwningVector<Expr*> ConstructorArgs(S);
4629 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4630 ? Kind.getEqualLoc()
4631 : Kind.getLocation();
4632
4633 if (Kind.getKind() == InitializationKind::IK_Default) {
4634 // Force even a trivial, implicit default constructor to be
4635 // semantically checked. We do this explicitly because we don't build
4636 // the definition for completely trivial constructors.
4637 CXXRecordDecl *ClassDecl = Constructor->getParent();
4638 assert(ClassDecl && "No parent class for constructor.");
4639 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4640 ClassDecl->hasTrivialDefaultConstructor() &&
4641 !Constructor->isUsed(false))
4642 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4643 }
4644
4645 ExprResult CurInit = S.Owned((Expr *)0);
4646
4647 // Determine the arguments required to actually perform the constructor
4648 // call.
4649 if (S.CompleteConstructorCall(Constructor, move(Args),
4650 Loc, ConstructorArgs))
4651 return ExprError();
4652
4653
4654 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4655 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4656 (Kind.getKind() == InitializationKind::IK_Direct ||
4657 Kind.getKind() == InitializationKind::IK_Value)) {
4658 // An explicitly-constructed temporary, e.g., X(1, 2).
4659 unsigned NumExprs = ConstructorArgs.size();
4660 Expr **Exprs = (Expr **)ConstructorArgs.take();
4661 S.MarkDeclarationReferenced(Loc, Constructor);
4662 S.DiagnoseUseOfDecl(Constructor, Loc);
4663
4664 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4665 if (!TSInfo)
4666 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4667
4668 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4669 Constructor,
4670 TSInfo,
4671 Exprs,
4672 NumExprs,
4673 Kind.getParenRange(),
4674 HadMultipleCandidates,
4675 ConstructorInitRequiresZeroInit));
4676 } else {
4677 CXXConstructExpr::ConstructionKind ConstructKind =
4678 CXXConstructExpr::CK_Complete;
4679
4680 if (Entity.getKind() == InitializedEntity::EK_Base) {
4681 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4682 CXXConstructExpr::CK_VirtualBase :
4683 CXXConstructExpr::CK_NonVirtualBase;
4684 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4685 ConstructKind = CXXConstructExpr::CK_Delegating;
4686 }
4687
4688 // Only get the parenthesis range if it is a direct construction.
4689 SourceRange parenRange =
4690 Kind.getKind() == InitializationKind::IK_Direct ?
4691 Kind.getParenRange() : SourceRange();
4692
4693 // If the entity allows NRVO, mark the construction as elidable
4694 // unconditionally.
4695 if (Entity.allowsNRVO())
4696 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4697 Constructor, /*Elidable=*/true,
4698 move_arg(ConstructorArgs),
4699 HadMultipleCandidates,
4700 ConstructorInitRequiresZeroInit,
4701 ConstructKind,
4702 parenRange);
4703 else
4704 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4705 Constructor,
4706 move_arg(ConstructorArgs),
4707 HadMultipleCandidates,
4708 ConstructorInitRequiresZeroInit,
4709 ConstructKind,
4710 parenRange);
4711 }
4712 if (CurInit.isInvalid())
4713 return ExprError();
4714
4715 // Only check access if all of that succeeded.
4716 S.CheckConstructorAccess(Loc, Constructor, Entity,
4717 Step.Function.FoundDecl.getAccess());
4718 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4719
4720 if (shouldBindAsTemporary(Entity))
4721 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4722
4723 return move(CurInit);
4724}
4725
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004726ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004727InitializationSequence::Perform(Sema &S,
4728 const InitializedEntity &Entity,
4729 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004730 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004731 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004732 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004733 unsigned NumArgs = Args.size();
4734 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004735 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Sebastian Redld201edf2011-06-05 13:59:11 +00004738 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004739 // If the declaration is a non-dependent, incomplete array type
4740 // that has an initializer, then its type will be completed once
4741 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004742 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004743 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004744 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004745 if (const IncompleteArrayType *ArrayT
4746 = S.Context.getAsIncompleteArrayType(DeclType)) {
4747 // FIXME: We don't currently have the ability to accurately
4748 // compute the length of an initializer list without
4749 // performing full type-checking of the initializer list
4750 // (since we have to determine where braces are implicitly
4751 // introduced and such). So, we fall back to making the array
4752 // type a dependently-sized array type with no specified
4753 // bound.
4754 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4755 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004756
Douglas Gregor51e77d52009-12-10 17:56:55 +00004757 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004758 if (DeclaratorDecl *DD = Entity.getDecl()) {
4759 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4760 TypeLoc TL = TInfo->getTypeLoc();
4761 if (IncompleteArrayTypeLoc *ArrayLoc
4762 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4763 Brackets = ArrayLoc->getBracketsRange();
4764 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004765 }
4766
4767 *ResultType
4768 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4769 /*NumElts=*/0,
4770 ArrayT->getSizeModifier(),
4771 ArrayT->getIndexTypeCVRQualifiers(),
4772 Brackets);
4773 }
4774
4775 }
4776 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004777 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4778 Kind.isExplicitCast());
4779 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004780 }
4781
Sebastian Redld201edf2011-06-05 13:59:11 +00004782 // No steps means no initialization.
4783 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004784 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Douglas Gregor1b303932009-12-22 15:35:07 +00004786 QualType DestType = Entity.getType().getNonReferenceType();
4787 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004788 // the same as Entity.getDecl()->getType() in cases involving type merging,
4789 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004790 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004791 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004792 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004793
John McCalldadc5752010-08-24 06:29:42 +00004794 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004797 // grab the only argument out the Args and place it into the "current"
4798 // initializer.
4799 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004800 case SK_ResolveAddressOfOverloadedFunction:
4801 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004802 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004803 case SK_CastDerivedToBaseLValue:
4804 case SK_BindReference:
4805 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004806 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004807 case SK_UserConversion:
4808 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004809 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004810 case SK_QualificationConversionRValue:
4811 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004812 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004813 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004814 case SK_UnwrapInitList:
4815 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004816 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004817 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004818 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004819 case SK_ArrayInit:
4820 case SK_PassByIndirectCopyRestore:
4821 case SK_PassByIndirectRestore:
4822 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004823 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004824 CurInit = Args.get()[0];
4825 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004826 break;
John McCall34376a62010-12-04 03:47:34 +00004827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Douglas Gregore1314a62009-12-18 05:02:21 +00004829 case SK_ConstructorInitialization:
4830 case SK_ZeroInitialization:
4831 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
4834 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004836 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004837 for (step_iterator Step = step_begin(), StepEnd = step_end();
4838 Step != StepEnd; ++Step) {
4839 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004840 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
John Wiegley01296292011-04-08 18:41:53 +00004842 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004844 switch (Step->Kind) {
4845 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004847 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004848 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004849 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004850 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004851 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004852 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004853 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004854
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004855 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004856 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004857 case SK_CastDerivedToBaseLValue: {
4858 // We have a derived-to-base cast that produces either an rvalue or an
4859 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860
John McCallcf142162010-08-07 06:22:56 +00004861 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004862
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004863 // Casts to inaccessible base classes are allowed with C-style casts.
4864 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4865 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004866 CurInit.get()->getLocStart(),
4867 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004868 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004869 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004870
Douglas Gregor88d292c2010-05-13 16:44:06 +00004871 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4872 QualType T = SourceType;
4873 if (const PointerType *Pointer = T->getAs<PointerType>())
4874 T = Pointer->getPointeeType();
4875 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004876 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004877 cast<CXXRecordDecl>(RecordTy->getDecl()));
4878 }
4879
John McCall2536c6d2010-08-25 10:28:54 +00004880 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004881 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004882 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004883 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004884 VK_XValue :
4885 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004886 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4887 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004888 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004889 CurInit.get(),
4890 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004891 break;
4892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004894 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004895 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004896 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4897 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004898 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004899 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004900 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004901 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004902 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004903 }
Anders Carlssona91be642010-01-29 02:47:33 +00004904
John Wiegley01296292011-04-08 18:41:53 +00004905 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004906 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004907 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4908 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004909 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004910 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004911 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004913
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004914 // Reference binding does not have any corresponding ASTs.
4915
4916 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004917 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004918 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004919
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004920 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004922 case SK_BindReferenceToTemporary:
4923 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004924 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004925 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004926
Douglas Gregorfe314812011-06-21 17:03:29 +00004927 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004928 CurInit = new (S.Context) MaterializeTemporaryExpr(
4929 Entity.getType().getNonReferenceType(),
4930 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004931 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004932
4933 // If we're binding to an Objective-C object that has lifetime, we
4934 // need cleanups.
4935 if (S.getLangOptions().ObjCAutoRefCount &&
4936 CurInit.get()->getType()->isObjCLifetimeType())
4937 S.ExprNeedsCleanups = true;
4938
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004939 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004941 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004943 /*IsExtraneousCopy=*/true);
4944 break;
4945
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004946 case SK_UserConversion: {
4947 // We have a user-defined conversion that invokes either a constructor
4948 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004949 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004950 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004951 FunctionDecl *Fn = Step->Function.Function;
4952 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004953 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004954 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004955 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004956 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004957 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004958 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004959 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004960
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 // Determine the arguments required to actually perform the constructor
4962 // call.
John Wiegley01296292011-04-08 18:41:53 +00004963 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004964 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004965 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004966 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004967 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004969 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004971 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004972 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004973 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004974 CXXConstructExpr::CK_Complete,
4975 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004976 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004977 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004978
Anders Carlssona01874b2010-04-21 18:47:17 +00004979 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004980 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004981 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982
John McCalle3027922010-08-25 11:45:40 +00004983 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004984 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4985 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4986 S.IsDerivedFrom(SourceType, Class))
4987 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988
Douglas Gregor95562572010-04-24 23:45:46 +00004989 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004990 } else {
4991 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004992 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004993 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004994 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004995 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996
4997 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004998 // derived-to-base conversion? I believe the answer is "no", because
4999 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005000 ExprResult CurInitExprRes =
5001 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5002 FoundFn, Conversion);
5003 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005004 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005005 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005007 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005008 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5009 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005010 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005011 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
John McCalle3027922010-08-25 11:45:40 +00005013 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
Douglas Gregor95562572010-04-24 23:45:46 +00005015 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017
Sebastian Redl112aa822011-07-14 19:07:55 +00005018 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005019 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5020
5021 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005022 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005023 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005025 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005026 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005027 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00005028 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
5029 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005030 }
5031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032
John McCallcf142162010-08-07 06:22:56 +00005033 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005034 CurInit.get()->getType(),
5035 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005036 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005037 if (MaybeBindToTemp)
5038 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005039 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005040 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5041 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005042 break;
5043 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005044
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005045 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005046 case SK_QualificationConversionXValue:
5047 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005048 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005049 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005050 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005051 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005052 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005053 VK_XValue :
5054 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005055 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005056 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005057 }
5058
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005059 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005060 Sema::CheckedConversionKind CCK
5061 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5062 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005063 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005064 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005065 ExprResult CurInitExprRes =
5066 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005067 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005068 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005069 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005070 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005071 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Douglas Gregor51e77d52009-12-10 17:56:55 +00005074 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005075 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005076 // Hack: We must pass *ResultType if available in order to set the type
5077 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5078 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5079 // temporary, not a reference, so we should pass Ty.
5080 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5081 // Since this step is never used for a reference directly, we explicitly
5082 // unwrap references here and rewrap them afterwards.
5083 // We also need to create a InitializeTemporary entity for this.
5084 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5085 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5086 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5087 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5088 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005089 Kind.getKind() != InitializationKind::IK_Direct ||
5090 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005091 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005092 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005093
Sebastian Redl29526f02011-11-27 16:50:07 +00005094 if (ResultType) {
5095 if ((*ResultType)->isRValueReferenceType())
5096 Ty = S.Context.getRValueReferenceType(Ty);
5097 else if ((*ResultType)->isLValueReferenceType())
5098 Ty = S.Context.getLValueReferenceType(Ty,
5099 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5100 *ResultType = Ty;
5101 }
5102
5103 InitListExpr *StructuredInitList =
5104 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005105 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005106 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005107 break;
5108 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005109
Sebastian Redled2e5322011-12-22 14:44:04 +00005110 case SK_ListConstructorCall: {
5111 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5112 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5113 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5114 move(Arg), *Step,
5115 ConstructorInitRequiresZeroInit);
5116 break;
5117 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005118
Sebastian Redl29526f02011-11-27 16:50:07 +00005119 case SK_UnwrapInitList:
5120 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5121 break;
5122
5123 case SK_RewrapInitList: {
5124 Expr *E = CurInit.take();
5125 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5126 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5127 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5128 ILE->setSyntacticForm(Syntactic);
5129 ILE->setType(E->getType());
5130 ILE->setValueKind(E->getValueKind());
5131 CurInit = S.Owned(ILE);
5132 break;
5133 }
5134
Sebastian Redled2e5322011-12-22 14:44:04 +00005135 case SK_ConstructorInitialization:
5136 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5137 *Step,
5138 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005139 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005140
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005141 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005142 step_iterator NextStep = Step;
5143 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005145 NextStep->Kind == SK_ConstructorInitialization) {
5146 // The need for zero-initialization is recorded directly into
5147 // the call to the object's constructor within the next step.
5148 ConstructorInitRequiresZeroInit = true;
5149 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5150 S.getLangOptions().CPlusPlus &&
5151 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005152 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5153 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005154 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005155 Kind.getRange().getBegin());
5156
5157 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5158 TSInfo->getType().getNonLValueExprType(S.Context),
5159 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005160 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005161 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005162 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005163 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005164 break;
5165 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005166
5167 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005168 QualType SourceType = CurInit.get()->getType();
5169 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005170 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005171 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5172 if (Result.isInvalid())
5173 return ExprError();
5174 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005175
5176 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005177 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005178 if (ConvTy != Sema::Compatible &&
5179 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005180 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005181 == Sema::Compatible)
5182 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005183 if (CurInitExprRes.isInvalid())
5184 return ExprError();
5185 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005186
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005187 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005188 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5189 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005190 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005191 getAssignmentAction(Entity),
5192 &Complained)) {
5193 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005194 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005195 } else if (Complained)
5196 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005197 break;
5198 }
Eli Friedman78275202009-12-19 08:11:05 +00005199
5200 case SK_StringInit: {
5201 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005202 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005203 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005204 break;
5205 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005206
5207 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005208 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005209 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005210 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005211 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005212
5213 case SK_ArrayInit:
5214 // Okay: we checked everything before creating this step. Note that
5215 // this is a GNU extension.
5216 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005217 << Step->Type << CurInit.get()->getType()
5218 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005219
5220 // If the destination type is an incomplete array type, update the
5221 // type accordingly.
5222 if (ResultType) {
5223 if (const IncompleteArrayType *IncompleteDest
5224 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5225 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005226 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005227 *ResultType = S.Context.getConstantArrayType(
5228 IncompleteDest->getElementType(),
5229 ConstantSource->getSize(),
5230 ArrayType::Normal, 0);
5231 }
5232 }
5233 }
John McCall31168b02011-06-15 23:02:42 +00005234 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005235
John McCall31168b02011-06-15 23:02:42 +00005236 case SK_PassByIndirectCopyRestore:
5237 case SK_PassByIndirectRestore:
5238 checkIndirectCopyRestoreSource(S, CurInit.get());
5239 CurInit = S.Owned(new (S.Context)
5240 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5241 Step->Kind == SK_PassByIndirectCopyRestore));
5242 break;
5243
5244 case SK_ProduceObjCObject:
5245 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005246 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005247 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005248 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005249 }
5250 }
John McCall1f425642010-11-11 03:21:53 +00005251
5252 // Diagnose non-fatal problems with the completed initialization.
5253 if (Entity.getKind() == InitializedEntity::EK_Member &&
5254 cast<FieldDecl>(Entity.getDecl())->isBitField())
5255 S.CheckBitFieldInitialization(Kind.getLocation(),
5256 cast<FieldDecl>(Entity.getDecl()),
5257 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005259 return move(CurInit);
5260}
5261
5262//===----------------------------------------------------------------------===//
5263// Diagnose initialization failures
5264//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005265bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005266 const InitializedEntity &Entity,
5267 const InitializationKind &Kind,
5268 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005269 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005270 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
Douglas Gregor1b303932009-12-22 15:35:07 +00005272 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 switch (Failure) {
5274 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005275 // FIXME: Customize for the initialized entity?
5276 if (NumArgs == 0)
5277 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5278 << DestType.getNonReferenceType();
5279 else // FIXME: diagnostic below could be better!
5280 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5281 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005282 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005284 case FK_ArrayNeedsInitList:
5285 case FK_ArrayNeedsInitListOrStringLiteral:
5286 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5287 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5288 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005289
Douglas Gregore2f943b2011-02-22 18:29:51 +00005290 case FK_ArrayTypeMismatch:
5291 case FK_NonConstantArrayInit:
5292 S.Diag(Kind.getLocation(),
5293 (Failure == FK_ArrayTypeMismatch
5294 ? diag::err_array_init_different_type
5295 : diag::err_array_init_non_constant_array))
5296 << DestType.getNonReferenceType()
5297 << Args[0]->getType()
5298 << Args[0]->getSourceRange();
5299 break;
5300
John McCalla59dc2f2012-01-05 00:13:19 +00005301 case FK_VariableLengthArrayHasInitializer:
5302 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5303 << Args[0]->getSourceRange();
5304 break;
5305
John McCall16df1e52010-03-30 21:47:33 +00005306 case FK_AddressOfOverloadFailed: {
5307 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005308 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005309 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005310 true,
5311 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 break;
John McCall16df1e52010-03-30 21:47:33 +00005313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005315 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005316 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005317 switch (FailedOverloadResult) {
5318 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005319 if (Failure == FK_UserConversionOverloadFailed)
5320 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5321 << Args[0]->getType() << DestType
5322 << Args[0]->getSourceRange();
5323 else
5324 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5325 << DestType << Args[0]->getType()
5326 << Args[0]->getSourceRange();
5327
John McCall5c32be02010-08-24 20:38:10 +00005328 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005329 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005330
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 case OR_No_Viable_Function:
5332 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5333 << Args[0]->getType() << DestType.getNonReferenceType()
5334 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005335 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005336 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005337
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005338 case OR_Deleted: {
5339 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5340 << Args[0]->getType() << DestType.getNonReferenceType()
5341 << Args[0]->getSourceRange();
5342 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005343 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005344 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5345 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005346 if (Ovl == OR_Deleted) {
5347 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005348 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005349 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005350 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005351 }
5352 break;
5353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005355 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005356 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005357 }
5358 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005359
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005360 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005361 if (isa<InitListExpr>(Args[0])) {
5362 S.Diag(Kind.getLocation(),
5363 diag::err_lvalue_reference_bind_to_initlist)
5364 << DestType.getNonReferenceType().isVolatileQualified()
5365 << DestType.getNonReferenceType()
5366 << Args[0]->getSourceRange();
5367 break;
5368 }
5369 // Intentional fallthrough
5370
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005371 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005373 Failure == FK_NonConstLValueReferenceBindingToTemporary
5374 ? diag::err_lvalue_reference_bind_to_temporary
5375 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005376 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005377 << DestType.getNonReferenceType()
5378 << Args[0]->getType()
5379 << Args[0]->getSourceRange();
5380 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005381
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005382 case FK_RValueReferenceBindingToLValue:
5383 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005384 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005385 << Args[0]->getSourceRange();
5386 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005387
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005388 case FK_ReferenceInitDropsQualifiers:
5389 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5390 << DestType.getNonReferenceType()
5391 << Args[0]->getType()
5392 << Args[0]->getSourceRange();
5393 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005394
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005395 case FK_ReferenceInitFailed:
5396 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5397 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005398 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005399 << Args[0]->getType()
5400 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005401 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5402 Args[0]->getType()->isObjCObjectPointerType())
5403 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005404 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
Douglas Gregorb491ed32011-02-19 21:32:49 +00005406 case FK_ConversionFailed: {
5407 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005408 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005409 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005410 << DestType
John McCall086a4642010-11-24 05:12:34 +00005411 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005412 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005413 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005414 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5415 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005416 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5417 Args[0]->getType()->isObjCObjectPointerType())
5418 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005419 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005420 }
John Wiegley01296292011-04-08 18:41:53 +00005421
5422 case FK_ConversionFromPropertyFailed:
5423 // No-op. This error has already been reported.
5424 break;
5425
Douglas Gregor51e77d52009-12-10 17:56:55 +00005426 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005427 SourceRange R;
5428
5429 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005430 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005431 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005432 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005433 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005434
Douglas Gregor8ec51732010-09-08 21:40:08 +00005435 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5436 if (Kind.isCStyleOrFunctionalCast())
5437 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5438 << R;
5439 else
5440 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5441 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005442 break;
5443 }
5444
5445 case FK_ReferenceBindingToInitList:
5446 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5447 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5448 break;
5449
5450 case FK_InitListBadDestinationType:
5451 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5452 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5453 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005454
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005455 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005456 case FK_ConstructorOverloadFailed: {
5457 SourceRange ArgsRange;
5458 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005459 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005460 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005461
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005462 if (Failure == FK_ListConstructorOverloadFailed) {
5463 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5464 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5465 Args = InitList->getInits();
5466 NumArgs = InitList->getNumInits();
5467 }
5468
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005469 // FIXME: Using "DestType" for the entity we're printing is probably
5470 // bad.
5471 switch (FailedOverloadResult) {
5472 case OR_Ambiguous:
5473 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5474 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005475 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5476 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005477 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005479 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005480 if (Kind.getKind() == InitializationKind::IK_Default &&
5481 (Entity.getKind() == InitializedEntity::EK_Base ||
5482 Entity.getKind() == InitializedEntity::EK_Member) &&
5483 isa<CXXConstructorDecl>(S.CurContext)) {
5484 // This is implicit default initialization of a member or
5485 // base within a constructor. If no viable function was
5486 // found, notify the user that she needs to explicitly
5487 // initialize this base/member.
5488 CXXConstructorDecl *Constructor
5489 = cast<CXXConstructorDecl>(S.CurContext);
5490 if (Entity.getKind() == InitializedEntity::EK_Base) {
5491 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5492 << Constructor->isImplicit()
5493 << S.Context.getTypeDeclType(Constructor->getParent())
5494 << /*base=*/0
5495 << Entity.getType();
5496
5497 RecordDecl *BaseDecl
5498 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5499 ->getDecl();
5500 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5501 << S.Context.getTagDeclType(BaseDecl);
5502 } else {
5503 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5504 << Constructor->isImplicit()
5505 << S.Context.getTypeDeclType(Constructor->getParent())
5506 << /*member=*/1
5507 << Entity.getName();
5508 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5509
5510 if (const RecordType *Record
5511 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005512 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005513 diag::note_previous_decl)
5514 << S.Context.getTagDeclType(Record->getDecl());
5515 }
5516 break;
5517 }
5518
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005519 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5520 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005521 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005522 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005523
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005524 case OR_Deleted: {
5525 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5526 << true << DestType << ArgsRange;
5527 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005528 OverloadingResult Ovl
5529 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005530 if (Ovl == OR_Deleted) {
5531 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005532 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005533 } else {
5534 llvm_unreachable("Inconsistent overload resolution?");
5535 }
5536 break;
5537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005539 case OR_Success:
5540 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005541 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005542 }
David Blaikie60deeee2012-01-17 08:24:58 +00005543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregor85dabae2009-12-16 01:38:02 +00005545 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005546 if (Entity.getKind() == InitializedEntity::EK_Member &&
5547 isa<CXXConstructorDecl>(S.CurContext)) {
5548 // This is implicit default-initialization of a const member in
5549 // a constructor. Complain that it needs to be explicitly
5550 // initialized.
5551 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5552 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5553 << Constructor->isImplicit()
5554 << S.Context.getTypeDeclType(Constructor->getParent())
5555 << /*const=*/1
5556 << Entity.getName();
5557 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5558 << Entity.getName();
5559 } else {
5560 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5561 << DestType << (bool)DestType->getAs<RecordType>();
5562 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005565 case FK_Incomplete:
5566 S.RequireCompleteType(Kind.getLocation(), DestType,
5567 diag::err_init_incomplete_type);
5568 break;
5569
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005570 case FK_ListInitializationFailed: {
5571 // Run the init list checker again to emit diagnostics.
5572 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5573 QualType DestType = Entity.getType();
5574 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005575 DestType, /*VerifyOnly=*/false,
5576 Kind.getKind() != InitializationKind::IK_Direct ||
5577 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005578 assert(DiagnoseInitList.HadError() &&
5579 "Inconsistent init list check result.");
5580 break;
5581 }
John McCall4124c492011-10-17 18:40:02 +00005582
5583 case FK_PlaceholderType: {
5584 // FIXME: Already diagnosed!
5585 break;
5586 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005589 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005590 return true;
5591}
Douglas Gregore1314a62009-12-18 05:02:21 +00005592
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005593void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005594 switch (SequenceKind) {
5595 case FailedSequence: {
5596 OS << "Failed sequence: ";
5597 switch (Failure) {
5598 case FK_TooManyInitsForReference:
5599 OS << "too many initializers for reference";
5600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005602 case FK_ArrayNeedsInitList:
5603 OS << "array requires initializer list";
5604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005606 case FK_ArrayNeedsInitListOrStringLiteral:
5607 OS << "array requires initializer list or string literal";
5608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregore2f943b2011-02-22 18:29:51 +00005610 case FK_ArrayTypeMismatch:
5611 OS << "array type mismatch";
5612 break;
5613
5614 case FK_NonConstantArrayInit:
5615 OS << "non-constant array initializer";
5616 break;
5617
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005618 case FK_AddressOfOverloadFailed:
5619 OS << "address of overloaded function failed";
5620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005622 case FK_ReferenceInitOverloadFailed:
5623 OS << "overload resolution for reference initialization failed";
5624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005626 case FK_NonConstLValueReferenceBindingToTemporary:
5627 OS << "non-const lvalue reference bound to temporary";
5628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005630 case FK_NonConstLValueReferenceBindingToUnrelated:
5631 OS << "non-const lvalue reference bound to unrelated type";
5632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005634 case FK_RValueReferenceBindingToLValue:
5635 OS << "rvalue reference bound to an lvalue";
5636 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005638 case FK_ReferenceInitDropsQualifiers:
5639 OS << "reference initialization drops qualifiers";
5640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005642 case FK_ReferenceInitFailed:
5643 OS << "reference initialization failed";
5644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005646 case FK_ConversionFailed:
5647 OS << "conversion failed";
5648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
John Wiegley01296292011-04-08 18:41:53 +00005650 case FK_ConversionFromPropertyFailed:
5651 OS << "conversion from property failed";
5652 break;
5653
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005654 case FK_TooManyInitsForScalar:
5655 OS << "too many initializers for scalar";
5656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005658 case FK_ReferenceBindingToInitList:
5659 OS << "referencing binding to initializer list";
5660 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005662 case FK_InitListBadDestinationType:
5663 OS << "initializer list for non-aggregate, non-scalar type";
5664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005666 case FK_UserConversionOverloadFailed:
5667 OS << "overloading failed for user-defined conversion";
5668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005670 case FK_ConstructorOverloadFailed:
5671 OS << "constructor overloading failed";
5672 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005674 case FK_DefaultInitOfConst:
5675 OS << "default initialization of a const variable";
5676 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005678 case FK_Incomplete:
5679 OS << "initialization of incomplete type";
5680 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005681
5682 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005683 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005684 break;
5685
John McCalla59dc2f2012-01-05 00:13:19 +00005686 case FK_VariableLengthArrayHasInitializer:
5687 OS << "variable length array has an initializer";
5688 break;
5689
John McCall4124c492011-10-17 18:40:02 +00005690 case FK_PlaceholderType:
5691 OS << "initializer expression isn't contextually valid";
5692 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005693
5694 case FK_ListConstructorOverloadFailed:
5695 OS << "list constructor overloading failed";
5696 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005698 OS << '\n';
5699 return;
5700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005702 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005703 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005704 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705
Sebastian Redld201edf2011-06-05 13:59:11 +00005706 case NormalSequence:
5707 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005708 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005711 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5712 if (S != step_begin()) {
5713 OS << " -> ";
5714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005715
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005716 switch (S->Kind) {
5717 case SK_ResolveAddressOfOverloadedFunction:
5718 OS << "resolve address of overloaded function";
5719 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005721 case SK_CastDerivedToBaseRValue:
5722 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5723 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005725 case SK_CastDerivedToBaseXValue:
5726 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5727 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005728
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005729 case SK_CastDerivedToBaseLValue:
5730 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5731 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005733 case SK_BindReference:
5734 OS << "bind reference to lvalue";
5735 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005737 case SK_BindReferenceToTemporary:
5738 OS << "bind reference to a temporary";
5739 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005741 case SK_ExtraneousCopyToTemporary:
5742 OS << "extraneous C++03 copy to temporary";
5743 break;
5744
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005745 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005746 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005747 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005748
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005749 case SK_QualificationConversionRValue:
5750 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005751 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005752
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005753 case SK_QualificationConversionXValue:
5754 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005755 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005756
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005757 case SK_QualificationConversionLValue:
5758 OS << "qualification conversion (lvalue)";
5759 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005761 case SK_ConversionSequence:
5762 OS << "implicit conversion sequence (";
5763 S->ICS->DebugPrint(); // FIXME: use OS
5764 OS << ")";
5765 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005767 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005768 OS << "list aggregate initialization";
5769 break;
5770
5771 case SK_ListConstructorCall:
5772 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005773 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Sebastian Redl29526f02011-11-27 16:50:07 +00005775 case SK_UnwrapInitList:
5776 OS << "unwrap reference initializer list";
5777 break;
5778
5779 case SK_RewrapInitList:
5780 OS << "rewrap reference initializer list";
5781 break;
5782
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005783 case SK_ConstructorInitialization:
5784 OS << "constructor initialization";
5785 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005786
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005787 case SK_ZeroInitialization:
5788 OS << "zero initialization";
5789 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005791 case SK_CAssignment:
5792 OS << "C assignment";
5793 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005794
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005795 case SK_StringInit:
5796 OS << "string initialization";
5797 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005798
5799 case SK_ObjCObjectConversion:
5800 OS << "Objective-C object conversion";
5801 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005802
5803 case SK_ArrayInit:
5804 OS << "array initialization";
5805 break;
John McCall31168b02011-06-15 23:02:42 +00005806
5807 case SK_PassByIndirectCopyRestore:
5808 OS << "pass by indirect copy and restore";
5809 break;
5810
5811 case SK_PassByIndirectRestore:
5812 OS << "pass by indirect restore";
5813 break;
5814
5815 case SK_ProduceObjCObject:
5816 OS << "Objective-C object retension";
5817 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005818 }
5819 }
5820}
5821
5822void InitializationSequence::dump() const {
5823 dump(llvm::errs());
5824}
5825
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005826static void DiagnoseNarrowingInInitList(
5827 Sema& S, QualType EntityType, const Expr *InitE,
5828 bool Constant, const APValue &ConstantValue) {
5829 if (Constant) {
5830 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005831 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005832 ? diag::err_init_list_constant_narrowing
5833 : diag::warn_init_list_constant_narrowing)
5834 << InitE->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005835 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005836 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005837 } else
5838 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005839 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005840 ? diag::err_init_list_variable_narrowing
5841 : diag::warn_init_list_variable_narrowing)
5842 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005843 << InitE->getType().getLocalUnqualifiedType()
5844 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005845
5846 llvm::SmallString<128> StaticCast;
5847 llvm::raw_svector_ostream OS(StaticCast);
5848 OS << "static_cast<";
5849 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5850 // It's important to use the typedef's name if there is one so that the
5851 // fixit doesn't break code using types like int64_t.
5852 //
5853 // FIXME: This will break if the typedef requires qualification. But
5854 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005855 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005856 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5857 OS << BT->getName(S.getLangOptions());
5858 else {
5859 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5860 // with a broken cast.
5861 return;
5862 }
5863 OS << ">(";
5864 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5865 << InitE->getSourceRange()
5866 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5867 << FixItHint::CreateInsertion(
5868 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5869}
5870
Douglas Gregore1314a62009-12-18 05:02:21 +00005871//===----------------------------------------------------------------------===//
5872// Initialization helper functions
5873//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005874bool
5875Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5876 ExprResult Init) {
5877 if (Init.isInvalid())
5878 return false;
5879
5880 Expr *InitE = Init.get();
5881 assert(InitE && "No initialization expression");
5882
5883 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5884 SourceLocation());
5885 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005886 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005887}
5888
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005889ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005890Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5891 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005892 ExprResult Init,
5893 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005894 if (Init.isInvalid())
5895 return ExprError();
5896
John McCall1f425642010-11-11 03:21:53 +00005897 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005898 assert(InitE && "No initialization expression?");
5899
5900 if (EqualLoc.isInvalid())
5901 EqualLoc = InitE->getLocStart();
5902
5903 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5904 EqualLoc);
5905 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5906 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005907
5908 bool Constant = false;
5909 APValue Result;
5910 if (TopLevelOfInitList &&
5911 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5912 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5913 Constant, Result);
5914 }
John McCallfaf5fb42010-08-26 23:41:50 +00005915 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005916}