blob: 6cbc09eeaf30cb5310ea35f402f221b0979cec79 [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"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000176 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000178
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner9ececce2009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000275
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor2bb07652009-12-22 00:05:34 +0000314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000322
John McCalldadc5752010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000346}
347
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351void
Douglas Gregor723796a2009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000356 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 SourceLocation Loc = ILE->getSourceRange().getBegin();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
366 else {
367 unsigned Init = 0;
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
373 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000376 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000383
Douglas Gregor2bb07652009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump11289f42009-09-09 15:08:12 +0000391 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000409 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCalldadc5752010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 else
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000448 } else {
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453 return;
454 }
455
Sebastian Redld201edf2011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
463 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000464 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000471
Douglas Gregor723796a2009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000477
Eli Friedman23a9e312008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000485
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501 }
502 return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000518}
519
Anders Carlsson6cabf312010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Steve Narofff8ecff22008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000533 else
David Blaikie83d382b2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000535
Eli Friedmane0f832b2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000549 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000552
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000565
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000586 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000589 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000590 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000591}
592
Anders Carlsson6cabf312010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
607 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608 IList->setType(ExprTy);
609 StructuredList->setType(ExprTy);
610 }
Eli Friedman85f54972008-05-25 13:22:35 +0000611 if (hadError)
612 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613
Eli Friedman85f54972008-05-25 13:22:35 +0000614 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000616 if (VerifyOnly) {
617 if (SemaRef.getLangOptions().CPlusPlus ||
618 (SemaRef.getLangOptions().OpenCL &&
619 IList->getType()->isVectorType())) {
620 hadError = true;
621 }
622 return;
623 }
624
Eli Friedmanbd327452009-05-29 20:20:05 +0000625 if (StructuredIndex == 1 &&
626 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000630 hadError = true;
631 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000632 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000634 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000635 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000636 // Don't complain for incomplete types, since we'll get an error
637 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000639 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000640 CurrentObjectType->isArrayType()? 0 :
641 CurrentObjectType->isVectorType()? 1 :
642 CurrentObjectType->isScalarType()? 2 :
643 CurrentObjectType->isUnionType()? 3 :
644 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000645
646 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000647 if (SemaRef.getLangOptions().CPlusPlus) {
648 DK = diag::err_excess_initializers;
649 hadError = true;
650 }
Nate Begeman425038c2009-07-07 21:53:06 +0000651 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652 DK = diag::err_excess_initializers;
653 hadError = true;
654 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000655
Chris Lattnerb0912a52009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000657 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 }
659 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000660
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000661 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000664 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000665 << FixItHint::CreateRemoval(IList->getLocStart())
666 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000667}
668
Anders Carlsson6cabf312010-01-23 23:23:01 +0000669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000671 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000672 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000673 unsigned &Index,
674 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000675 unsigned &StructuredIndex,
676 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000677 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678 // Explicitly braced initializer for complex type can be real+imaginary
679 // parts.
680 CheckComplexType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
682 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000683 CheckScalarType(Entity, IList, DeclType, Index,
684 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000685 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000687 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000688 } else if (DeclType->isAggregateType()) {
689 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000690 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000691 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000693 StructuredList, StructuredIndex,
694 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000695 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000697 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000698 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000700 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000703 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000711 } else if (DeclType->isRecordType()) {
712 // C++ [dcl.init]p14:
713 // [...] If the class is an aggregate (8.5.1), and the initializer
714 // is a brace-enclosed list, see 8.5.1.
715 //
716 // Note: 8.5.1 is handled below; here, we diagnose the case where
717 // we have an initializer list and a destination type that is not
718 // an aggregate.
719 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000723 hadError = true;
724 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000725 CheckReferenceType(Entity, IList, DeclType, Index,
726 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000727 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 if (!VerifyOnly)
729 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000731 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000732 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000733 if (!VerifyOnly)
734 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000736 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000737 }
738}
739
Anders Carlsson6cabf312010-01-23 23:23:01 +0000740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000741 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000742 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000746 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751 = getStructuredSubobjectInit(IList, Index, ElemType,
752 StructuredList, StructuredIndex,
753 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000754 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 newStructuredList, newStructuredIndex);
756 ++StructuredIndex;
757 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000758 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000759 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000760 return CheckScalarType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000762 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000763 return CheckReferenceType(Entity, IList, ElemType, Index,
764 StructuredList, StructuredIndex);
765 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000766
John McCall5decec92011-02-21 07:57:55 +0000767 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768 // arrayType can be incomplete if we're initializing a flexible
769 // array member. There's nothing we can do with the completed
770 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000771
John McCall5decec92011-02-21 07:57:55 +0000772 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000773 if (!VerifyOnly) {
774 CheckStringInit(Str, ElemType, arrayType, SemaRef);
775 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000778 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000779 }
John McCall5decec92011-02-21 07:57:55 +0000780
781 // Fall through for subaggregate initialization.
782
783 } else if (SemaRef.getLangOptions().CPlusPlus) {
784 // C++ [dcl.init.aggr]p12:
785 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000786 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000787 // an initializer-list. If the initializer can initialize a
788 // member, the member is initialized. [...]
789
790 // FIXME: Better EqualLoc?
791 InitializationKind Kind =
792 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000797 ExprResult Result =
798 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799 if (Result.isInvalid())
800 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000801
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000803 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 }
John McCall5decec92011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 } else {
811 // C99 6.7.8p13:
812 //
813 // The initializer for a structure or union object that has
814 // automatic storage duration shall be either an initializer
815 // list as described below, or a single expression that has
816 // compatible structure or union type. In the latter case, the
817 // initial value of the object, including unnamed members, is
818 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000819 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000820 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000821 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000823 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000824 if (ExprRes.isInvalid())
825 hadError = true;
826 else {
827 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828 if (ExprRes.isInvalid())
829 hadError = true;
830 }
831 UpdateStructuredListElement(StructuredList, StructuredIndex,
832 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000833 ++Index;
834 return;
835 }
John Wiegley01296292011-04-08 18:41:53 +0000836 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000837 // Fall through for subaggregate initialization
838 }
839
840 // C++ [dcl.init.aggr]p12:
841 //
842 // [...] Otherwise, if the member is itself a non-empty
843 // subaggregate, brace elision is assumed and the initializer is
844 // considered for the initialization of the first member of
845 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000846 if (!SemaRef.getLangOptions().OpenCL &&
847 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000848 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849 StructuredIndex);
850 ++StructuredIndex;
851 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000852 if (!VerifyOnly) {
853 // We cannot initialize this element, so let
854 // PerformCopyInitialization produce the appropriate diagnostic.
855 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856 SemaRef.Owned(expr),
857 /*TopLevelOfInitList=*/true);
858 }
John McCall5decec92011-02-21 07:57:55 +0000859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000863}
864
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866 InitListExpr *IList, QualType DeclType,
867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
870 assert(Index == 0 && "Index in explicit init list must be zero");
871
872 // As an extension, clang supports complex initializers, which initialize
873 // a complex number component-wise. When an explicit initializer list for
874 // a complex number contains two two initializers, this extension kicks in:
875 // it exepcts the initializer list to contain two elements convertible to
876 // the element type of the complex type. The first element initializes
877 // the real part, and the second element intitializes the imaginary part.
878
879 if (IList->getNumInits() != 2)
880 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881 StructuredIndex);
882
883 // This is an extension in C. (The builtin _Complex type does not exist
884 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000885 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000886 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887 << IList->getSourceRange();
888
889 // Initialize the complex number.
890 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 for (unsigned i = 0; i < 2; ++i) {
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899}
900
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000904 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000907 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000908 if (!VerifyOnly)
909 SemaRef.Diag(IList->getLocStart(),
910 SemaRef.getLangOptions().CPlusPlus0x ?
911 diag::warn_cxx98_compat_empty_scalar_initializer :
912 diag::err_empty_scalar_initializer)
913 << IList->getSourceRange();
914 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000917 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000918 }
John McCall643169b2010-11-11 00:46:36 +0000919
920 Expr *expr = IList->getInit(Index);
921 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 if (!VerifyOnly)
923 SemaRef.Diag(SubIList->getLocStart(),
924 diag::warn_many_braces_around_scalar_init)
925 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000926
927 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928 StructuredIndex);
929 return;
930 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000931 if (!VerifyOnly)
932 SemaRef.Diag(expr->getSourceRange().getBegin(),
933 diag::err_designator_for_scalar_init)
934 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000935 hadError = true;
936 ++Index;
937 ++StructuredIndex;
938 return;
939 }
940
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 if (VerifyOnly) {
942 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 hadError = true;
944 ++Index;
945 return;
946 }
947
John McCall643169b2010-11-11 00:46:36 +0000948 ExprResult Result =
949 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000950 SemaRef.Owned(expr),
951 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000952
953 Expr *ResultExpr = 0;
954
955 if (Result.isInvalid())
956 hadError = true; // types weren't compatible.
957 else {
958 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000959
John McCall643169b2010-11-11 00:46:36 +0000960 if (ResultExpr != expr) {
961 // The type was promoted, update initializer list.
962 IList->setInit(Index, ResultExpr);
963 }
964 }
965 if (hadError)
966 ++StructuredIndex;
967 else
968 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000970}
971
Anders Carlsson6cabf312010-01-23 23:23:01 +0000972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000974 unsigned &Index,
975 InitListExpr *StructuredList,
976 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000977 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000978 // FIXME: It would be wonderful if we could point at the actual member. In
979 // general, it would be useful to pass location information down the stack,
980 // so that we know the location (or decl) of the "current object" being
981 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 if (!VerifyOnly)
983 SemaRef.Diag(IList->getLocStart(),
984 diag::err_init_reference_member_uninitialized)
985 << DeclType
986 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000987 hadError = true;
988 ++Index;
989 ++StructuredIndex;
990 return;
991 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000992
993 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000994 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000995 if (!VerifyOnly)
996 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997 << DeclType << IList->getSourceRange();
998 hadError = true;
999 ++Index;
1000 ++StructuredIndex;
1001 return;
1002 }
1003
1004 if (VerifyOnly) {
1005 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 hadError = true;
1007 ++Index;
1008 return;
1009 }
1010
1011 ExprResult Result =
1012 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013 SemaRef.Owned(expr),
1014 /*TopLevelOfInitList=*/true);
1015
1016 if (Result.isInvalid())
1017 hadError = true;
1018
1019 expr = Result.takeAs<Expr>();
1020 IList->setInit(Index, expr);
1021
1022 if (hadError)
1023 ++StructuredIndex;
1024 else
1025 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001027}
1028
Anders Carlsson6cabf312010-01-23 23:23:01 +00001029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001030 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
1033 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001034 const VectorType *VT = DeclType->getAs<VectorType>();
1035 unsigned maxElements = VT->getNumElements();
1036 unsigned numEltsInit = 0;
1037 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001038
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001039 if (Index >= IList->getNumInits()) {
1040 // Make sure the element type can be value-initialized.
1041 if (VerifyOnly)
1042 CheckValueInitializable(
1043 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044 return;
1045 }
1046
John McCall6a16b2f2010-10-30 00:11:39 +00001047 if (!SemaRef.getLangOptions().OpenCL) {
1048 // If the initializing element is a vector, try to copy-initialize
1049 // instead of breaking it apart (which is doomed to failure anyway).
1050 Expr *Init = IList->getInit(Index);
1051 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001052 if (VerifyOnly) {
1053 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 hadError = true;
1055 ++Index;
1056 return;
1057 }
1058
John McCall6a16b2f2010-10-30 00:11:39 +00001059 ExprResult Result =
1060 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001061 SemaRef.Owned(Init),
1062 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001063
1064 Expr *ResultExpr = 0;
1065 if (Result.isInvalid())
1066 hadError = true; // types weren't compatible.
1067 else {
1068 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069
John McCall6a16b2f2010-10-30 00:11:39 +00001070 if (ResultExpr != Init) {
1071 // The type was promoted, update initializer list.
1072 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001073 }
1074 }
John McCall6a16b2f2010-10-30 00:11:39 +00001075 if (hadError)
1076 ++StructuredIndex;
1077 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001078 UpdateStructuredListElement(StructuredList, StructuredIndex,
1079 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001080 ++Index;
1081 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCall6a16b2f2010-10-30 00:11:39 +00001084 InitializedEntity ElementEntity =
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
John McCall6a16b2f2010-10-30 00:11:39 +00001087 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001089 if (Index >= IList->getNumInits()) {
1090 if (VerifyOnly)
1091 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001092 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
John McCall6a16b2f2010-10-30 00:11:39 +00001095 ElementEntity.setElementIndex(Index);
1096 CheckSubElementType(ElementEntity, IList, elementType, Index,
1097 StructuredList, StructuredIndex);
1098 }
1099 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 }
John McCall6a16b2f2010-10-30 00:11:39 +00001101
1102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
John McCall6a16b2f2010-10-30 00:11:39 +00001105 // OpenCL initializers allows vectors to be constructed from vectors.
1106 for (unsigned i = 0; i < maxElements; ++i) {
1107 // Don't attempt to go past the end of the init list
1108 if (Index >= IList->getNumInits())
1109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
John McCall6a16b2f2010-10-30 00:11:39 +00001111 ElementEntity.setElementIndex(Index);
1112
1113 QualType IType = IList->getInit(Index)->getType();
1114 if (!IType->isVectorType()) {
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 ++numEltsInit;
1118 } else {
1119 QualType VecType;
1120 const VectorType *IVT = IType->getAs<VectorType>();
1121 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
John McCall6a16b2f2010-10-30 00:11:39 +00001123 if (IType->isExtVectorType())
1124 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125 else
1126 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001127 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001128 CheckSubElementType(ElementEntity, IList, VecType, Index,
1129 StructuredList, StructuredIndex);
1130 numEltsInit += numIElts;
1131 }
1132 }
1133
1134 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001135 if (numEltsInit != maxElements) {
1136 if (!VerifyOnly)
1137 SemaRef.Diag(IList->getSourceRange().getBegin(),
1138 diag::err_vector_incorrect_num_initializers)
1139 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140 hadError = true;
1141 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001142}
1143
Anders Carlsson6cabf312010-01-23 23:23:01 +00001144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001145 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001147 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001148 unsigned &Index,
1149 InitListExpr *StructuredList,
1150 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
Steve Narofff8ecff22008-05-01 22:18:59 +00001153 // Check for the special-case of initializing an array with a string.
1154 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001155 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001156 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001157 // We place the string literal directly into the resulting
1158 // initializer list. This is the only place where the structure
1159 // of the structured initializer list doesn't match exactly,
1160 // because doing so would involve allocating one character
1161 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001163 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001168 return;
1169 }
1170 }
John McCall66884dd2011-02-21 07:22:22 +00001171 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001172 // Check for VLAs; in standard C it would be possible to check this
1173 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 if (!VerifyOnly)
1176 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177 diag::err_variable_object_no_init)
1178 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001179 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 ++Index;
1181 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001182 return;
1183 }
1184
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001186 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001189 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001191 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001192 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001193 maxElementsKnown = true;
1194 }
1195
John McCall66884dd2011-02-21 07:22:22 +00001196 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001197 while (Index < IList->getNumInits()) {
1198 Expr *Init = IList->getInit(Index);
1199 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001200 // If we're not the subobject that matches up with the '{' for
1201 // the designator, we shouldn't be handling the
1202 // designator. Return immediately.
1203 if (!SubobjectIsDesignatorContext)
1204 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001205
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 // Handle this designated initializer. elementIndex will be
1207 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001208 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001210 StructuredList, StructuredIndex, true,
1211 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001212 hadError = true;
1213 continue;
1214 }
1215
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001218 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001219 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001221
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001222 // If the array is of incomplete type, keep track of the number of
1223 // elements in the initializer.
1224 if (!maxElementsKnown && elementIndex > maxElements)
1225 maxElements = elementIndex;
1226
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 continue;
1228 }
1229
1230 // If we know the maximum number of elements, and we've already
1231 // hit it, stop consuming elements in the initializer list.
1232 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001233 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 Entity);
1238 // Check this element.
1239 CheckSubElementType(ElementEntity, IList, elementType, Index,
1240 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001241 ++elementIndex;
1242
1243 // If the array is of incomplete type, keep track of the number of
1244 // elements in the initializer.
1245 if (!maxElementsKnown && elementIndex > maxElements)
1246 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001248 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001250 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001251 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001252 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001253 // Sizing an array implicitly to zero is not allowed by ISO C,
1254 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001255 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258
Mike Stump11289f42009-09-09 15:08:12 +00001259 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001260 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001261 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001262 if (!hadError && VerifyOnly) {
1263 // Check if there are any members of the array that get value-initialized.
1264 // If so, check if doing that is possible.
1265 // FIXME: This needs to detect holes left by designated initializers too.
1266 if (maxElementsKnown && elementIndex < maxElements)
1267 CheckValueInitializable(InitializedEntity::InitializeElement(
1268 SemaRef.Context, 0, Entity));
1269 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001270}
1271
Eli Friedman3fa64df2011-08-23 22:24:57 +00001272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273 Expr *InitExpr,
1274 FieldDecl *Field,
1275 bool TopLevelObject) {
1276 // Handle GNU flexible array initializers.
1277 unsigned FlexArrayDiag;
1278 if (isa<InitListExpr>(InitExpr) &&
1279 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280 // Empty flexible array init always allowed as an extension
1281 FlexArrayDiag = diag::ext_flexible_array_init;
1282 } else if (SemaRef.getLangOptions().CPlusPlus) {
1283 // Disallow flexible array init in C++; it is not required for gcc
1284 // compatibility, and it needs work to IRGen correctly in general.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (!TopLevelObject) {
1287 // Disallow flexible array init on non-top-level object
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290 // Disallow flexible array init on anything which is not a variable.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293 // Disallow flexible array init on local variables.
1294 FlexArrayDiag = diag::err_flexible_array_init;
1295 } else {
1296 // Allow other cases.
1297 FlexArrayDiag = diag::ext_flexible_array_init;
1298 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001299
1300 if (!VerifyOnly) {
1301 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302 FlexArrayDiag)
1303 << InitExpr->getSourceRange().getBegin();
1304 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305 << Field;
1306 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001307
1308 return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
Anders Carlsson6cabf312010-01-23 23:23:01 +00001311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001312 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001313 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001315 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001318 unsigned &StructuredIndex,
1319 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001320 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001321
Eli Friedman23a9e312008-05-19 19:16:24 +00001322 // If the record is invalid, some of it's members are invalid. To avoid
1323 // confusion, we forgo checking the intializer for the entire record.
1324 if (structDecl->isInvalidDecl()) {
1325 hadError = true;
1326 return;
Mike Stump11289f42009-09-09 15:08:12 +00001327 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001328
1329 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001330 // Value-initialize the first named member of the union.
1331 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333 Field != FieldEnd; ++Field) {
1334 if (Field->getDeclName()) {
1335 if (VerifyOnly)
1336 CheckValueInitializable(
1337 InitializedEntity::InitializeMember(*Field, &Entity));
1338 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001339 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001340 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001341 }
1342 }
1343 return;
1344 }
1345
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001346 // If structDecl is a forward declaration, this loop won't do
1347 // anything except look at designated initializers; That's okay,
1348 // because an error should get printed out elsewhere. It might be
1349 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001351 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001352 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001353 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001354 while (Index < IList->getNumInits()) {
1355 Expr *Init = IList->getInit(Index);
1356
1357 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 // If we're not the subobject that matches up with the '{' for
1359 // the designator, we shouldn't be handling the
1360 // designator. Return immediately.
1361 if (!SubobjectIsDesignatorContext)
1362 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001363
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001364 // Handle this designated initializer. Field will be updated to
1365 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001366 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001368 StructuredList, StructuredIndex,
1369 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001370 hadError = true;
1371
Douglas Gregora9add4e2009-02-12 19:00:39 +00001372 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001373
1374 // Disable check for missing fields when designators are used.
1375 // This matches gcc behaviour.
1376 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001377 continue;
1378 }
1379
1380 if (Field == FieldEnd) {
1381 // We've run out of fields. We're done.
1382 break;
1383 }
1384
Douglas Gregora9add4e2009-02-12 19:00:39 +00001385 // We've already initialized a member of a union. We're done.
1386 if (InitializedSomething && DeclType->isUnionType())
1387 break;
1388
Douglas Gregor91f84212008-12-11 16:49:14 +00001389 // If we've hit the flexible array member at the end, we're done.
1390 if (Field->getType()->isIncompleteArrayType())
1391 break;
1392
Douglas Gregor51695702009-01-29 16:53:55 +00001393 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001395 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001396 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001397 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001398
Douglas Gregora82064c2011-06-29 21:51:31 +00001399 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001400 bool InvalidUse;
1401 if (VerifyOnly)
1402 InvalidUse = !SemaRef.CanUseDecl(*Field);
1403 else
1404 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405 IList->getInit(Index)->getLocStart());
1406 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001407 ++Index;
1408 ++Field;
1409 hadError = true;
1410 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001411 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001412
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413 InitializedEntity MemberEntity =
1414 InitializedEntity::InitializeMember(*Field, &Entity);
1415 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001417 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001418
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001419 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001420 // Initialize the first field within the union.
1421 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001422 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001423
1424 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001425 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001426
John McCalle40b58e2010-03-11 19:32:38 +00001427 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001428 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001431 // It is possible we have one or more unnamed bitfields remaining.
1432 // Find first (if any) named field and emit warning.
1433 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434 it != end; ++it) {
1435 if (!it->isUnnamedBitfield()) {
1436 SemaRef.Diag(IList->getSourceRange().getEnd(),
1437 diag::warn_missing_field_initializers) << it->getName();
1438 break;
1439 }
1440 }
1441 }
1442
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001443 // Check that any remaining fields can be value-initialized.
1444 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445 !Field->getType()->isIncompleteArrayType()) {
1446 // FIXME: Should check for holes left by designated initializers too.
1447 for (; Field != FieldEnd && !hadError; ++Field) {
1448 if (!Field->isUnnamedBitfield())
1449 CheckValueInitializable(
1450 InitializedEntity::InitializeMember(*Field, &Entity));
1451 }
1452 }
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001455 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 return;
1457
Eli Friedman3fa64df2011-08-23 22:24:57 +00001458 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001461 ++Index;
1462 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 }
1464
Anders Carlsson6cabf312010-01-23 23:23:01 +00001465 InitializedEntity MemberEntity =
1466 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470 StructuredList, StructuredIndex);
1471 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001472 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001473 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001474}
Steve Narofff8ecff22008-05-01 22:18:59 +00001475
Douglas Gregord5846a12009-04-15 06:41:24 +00001476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
Douglas Gregord5846a12009-04-15 06:41:24 +00001480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001481 DesignatedInitExpr *DIE,
1482 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001483 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 typedef DesignatedInitExpr::Designator Designator;
1485
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001488 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001491 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001492 DIE->getDesignator(DesigIdx)->getDotLoc(),
1493 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494 else
1495 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001497 assert(isa<FieldDecl>(*PI));
1498 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001499 }
1500
1501 // Expand the current designator into the set of replacement
1502 // designators, so we have a full subobject path down to where the
1503 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001504 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001505 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001506}
Mike Stump11289f42009-09-09 15:08:12 +00001507
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001509/// corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511 IdentifierInfo *FieldName) {
1512 assert(AnonField->isAnonymousStructOrUnion());
1513 Decl *NextDecl = AnonField->getNextDeclInContext();
1514 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1515 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1516 return IF;
1517 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001518 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001519 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001520}
1521
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001522static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1523 DesignatedInitExpr *DIE) {
1524 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1525 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1526 for (unsigned I = 0; I < NumIndexExprs; ++I)
1527 IndexExprs[I] = DIE->getSubExpr(I + 1);
1528 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1529 DIE->size(), IndexExprs.data(),
1530 NumIndexExprs, DIE->getEqualOrColonLoc(),
1531 DIE->usesGNUSyntax(), DIE->getInit());
1532}
1533
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001534namespace {
1535
1536// Callback to only accept typo corrections that are for field members of
1537// the given struct or union.
1538class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1539 public:
1540 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1541 : Record(RD) {}
1542
1543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1544 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1545 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1546 }
1547
1548 private:
1549 RecordDecl *Record;
1550};
1551
1552}
1553
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001554/// @brief Check the well-formedness of a C99 designated initializer.
1555///
1556/// Determines whether the designated initializer @p DIE, which
1557/// resides at the given @p Index within the initializer list @p
1558/// IList, is well-formed for a current object of type @p DeclType
1559/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001560/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001562///
1563/// @param IList The initializer list in which this designated
1564/// initializer occurs.
1565///
Douglas Gregora5324162009-04-15 04:56:10 +00001566/// @param DIE The designated initializer expression.
1567///
1568/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001569///
1570/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1571/// into which the designation in @p DIE should refer.
1572///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573/// @param NextField If non-NULL and the first designator in @p DIE is
1574/// a field, this will be set to the field declaration corresponding
1575/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001576///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577/// @param NextElementIndex If non-NULL and the first designator in @p
1578/// DIE is an array designator or GNU array-range designator, this
1579/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001580///
1581/// @param Index Index into @p IList where the designated initializer
1582/// @p DIE occurs.
1583///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001584/// @param StructuredList The initializer list expression that
1585/// describes all of the subobject initializers in the order they'll
1586/// actually be initialized.
1587///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001588/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001589bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001590InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001591 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001592 DesignatedInitExpr *DIE,
1593 unsigned DesigIdx,
1594 QualType &CurrentObjectType,
1595 RecordDecl::field_iterator *NextField,
1596 llvm::APSInt *NextElementIndex,
1597 unsigned &Index,
1598 InitListExpr *StructuredList,
1599 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001600 bool FinishSubobjectInit,
1601 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001602 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 // Check the actual initialization for the designated object type.
1604 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001605
1606 // Temporarily remove the designator expression from the
1607 // initializer list that the child calls see, so that we don't try
1608 // to re-process the designator.
1609 unsigned OldIndex = Index;
1610 IList->setInit(OldIndex, DIE->getInit());
1611
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001612 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001613 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001614
1615 // Restore the designated initializer expression in the syntactic
1616 // form of the initializer list.
1617 if (IList->getInit(OldIndex) != DIE->getInit())
1618 DIE->setInit(IList->getInit(OldIndex));
1619 IList->setInit(OldIndex, DIE);
1620
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001622 }
1623
Douglas Gregora5324162009-04-15 04:56:10 +00001624 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001625 bool IsFirstDesignator = (DesigIdx == 0);
1626 if (!VerifyOnly) {
1627 assert((IsFirstDesignator || StructuredList) &&
1628 "Need a non-designated initializer list to start from");
1629
1630 // Determine the structural initializer list that corresponds to the
1631 // current subobject.
1632 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1633 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1634 StructuredList, StructuredIndex,
1635 SourceRange(D->getStartLocation(),
1636 DIE->getSourceRange().getEnd()));
1637 assert(StructuredList && "Expected a structured initializer list");
1638 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 if (D->isFieldDesignator()) {
1641 // C99 6.7.8p7:
1642 //
1643 // If a designator has the form
1644 //
1645 // . identifier
1646 //
1647 // then the current object (defined below) shall have
1648 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001649 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001650 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001651 if (!RT) {
1652 SourceLocation Loc = D->getDotLoc();
1653 if (Loc.isInvalid())
1654 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001655 if (!VerifyOnly)
1656 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1657 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 ++Index;
1659 return true;
1660 }
1661
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 // Note: we perform a linear search of the fields here, despite
1663 // the fact that we have a faster lookup method, because we always
1664 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001665 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001666 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001667 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001668 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001669 Field = RT->getDecl()->field_begin(),
1670 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 for (; Field != FieldEnd; ++Field) {
1672 if (Field->isUnnamedBitfield())
1673 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001675 // If we find a field representing an anonymous field, look in the
1676 // IndirectFieldDecl that follow for the designated initializer.
1677 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1678 if (IndirectFieldDecl *IF =
1679 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001680 // In verify mode, don't modify the original.
1681 if (VerifyOnly)
1682 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001683 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1684 D = DIE->getDesignator(DesigIdx);
1685 break;
1686 }
1687 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001688 if (KnownField && KnownField == *Field)
1689 break;
1690 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 break;
1692
1693 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001694 }
1695
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001697 if (VerifyOnly) {
1698 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001700 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001701
Douglas Gregord5846a12009-04-15 06:41:24 +00001702 // There was no normal field in the struct with the designated
1703 // name. Perform another lookup for this name, which may find
1704 // something that we can't designate (e.g., a member function),
1705 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001706 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001707 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001710 // Name lookup didn't find anything. Determine whether this
1711 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001712 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001713 TypoCorrection Corrected = SemaRef.CorrectTypo(
1714 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001715 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001716 RT->getDecl());
1717 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001718 std::string CorrectedStr(
1719 Corrected.getAsString(SemaRef.getLangOptions()));
1720 std::string CorrectedQuotedStr(
1721 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001722 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001724 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001725 << FieldName << CurrentObjectType << CorrectedQuotedStr
1726 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001728 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001729 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001730 } else {
1731 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1732 << FieldName << CurrentObjectType;
1733 ++Index;
1734 return true;
1735 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001738 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001740 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001742 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001744 ++Index;
1745 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001746 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001747
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001748 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001749 // The replacement field comes from typo correction; find it
1750 // in the list of fields.
1751 FieldIndex = 0;
1752 Field = RT->getDecl()->field_begin();
1753 for (; Field != FieldEnd; ++Field) {
1754 if (Field->isUnnamedBitfield())
1755 continue;
1756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001758 Field->getIdentifier() == ReplacementField->getIdentifier())
1759 break;
1760
1761 ++FieldIndex;
1762 }
1763 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001764 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765
1766 // All of the fields of a union are located at the same place in
1767 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001768 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001770 if (!VerifyOnly)
1771 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001772 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773
Douglas Gregora82064c2011-06-29 21:51:31 +00001774 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001775 bool InvalidUse;
1776 if (VerifyOnly)
1777 InvalidUse = !SemaRef.CanUseDecl(*Field);
1778 else
1779 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1780 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001781 ++Index;
1782 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001784
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001785 if (!VerifyOnly) {
1786 // Update the designator with the field declaration.
1787 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001789 // Make sure that our non-designated initializer list has space
1790 // for a subobject corresponding to this field.
1791 if (FieldIndex >= StructuredList->getNumInits())
1792 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1793 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001795 // This designator names a flexible array member.
1796 if (Field->getType()->isIncompleteArrayType()) {
1797 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001798 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001799 // We can't designate an object within the flexible array
1800 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001801 if (!VerifyOnly) {
1802 DesignatedInitExpr::Designator *NextD
1803 = DIE->getDesignator(DesigIdx + 1);
1804 SemaRef.Diag(NextD->getStartLocation(),
1805 diag::err_designator_into_flexible_array_member)
1806 << SourceRange(NextD->getStartLocation(),
1807 DIE->getSourceRange().getEnd());
1808 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1809 << *Field;
1810 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001811 Invalid = true;
1812 }
1813
Chris Lattner001b29c2010-10-10 17:49:49 +00001814 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1815 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001816 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001817 if (!VerifyOnly) {
1818 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1819 diag::err_flexible_array_init_needs_braces)
1820 << DIE->getInit()->getSourceRange();
1821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1822 << *Field;
1823 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001824 Invalid = true;
1825 }
1826
Eli Friedman3fa64df2011-08-23 22:24:57 +00001827 // Check GNU flexible array initializer.
1828 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1829 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001830 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001831
1832 if (Invalid) {
1833 ++Index;
1834 return true;
1835 }
1836
1837 // Initialize the array.
1838 bool prevHadError = hadError;
1839 unsigned newStructuredIndex = FieldIndex;
1840 unsigned OldIndex = Index;
1841 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001842
1843 InitializedEntity MemberEntity =
1844 InitializedEntity::InitializeMember(*Field, &Entity);
1845 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001847
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001848 IList->setInit(OldIndex, DIE);
1849 if (hadError && !prevHadError) {
1850 ++Field;
1851 ++FieldIndex;
1852 if (NextField)
1853 *NextField = Field;
1854 StructuredIndex = FieldIndex;
1855 return true;
1856 }
1857 } else {
1858 // Recurse to check later designated subobjects.
1859 QualType FieldType = (*Field)->getType();
1860 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001862 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001863 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1865 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001866 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001867 true, false))
1868 return true;
1869 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001870
1871 // Find the position of the next field to be initialized in this
1872 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001875
1876 // If this the first designator, our caller will continue checking
1877 // the rest of this struct/class/union subobject.
1878 if (IsFirstDesignator) {
1879 if (NextField)
1880 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001882 return false;
1883 }
1884
Douglas Gregor17bd0942009-01-28 23:36:17 +00001885 if (!FinishSubobjectInit)
1886 return false;
1887
Douglas Gregord5846a12009-04-15 06:41:24 +00001888 // We've already initialized something in the union; we're done.
1889 if (RT->getDecl()->isUnion())
1890 return hadError;
1891
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001892 // Check the remaining fields within this class/struct/union subobject.
1893 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Anders Carlsson6cabf312010-01-23 23:23:01 +00001895 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001897 return hadError && !prevHadError;
1898 }
1899
1900 // C99 6.7.8p6:
1901 //
1902 // If a designator has the form
1903 //
1904 // [ constant-expression ]
1905 //
1906 // then the current object (defined below) shall have array
1907 // type and the expression shall be an integer constant
1908 // expression. If the array is of unknown size, any
1909 // nonnegative value is valid.
1910 //
1911 // Additionally, cope with the GNU extension that permits
1912 // designators of the form
1913 //
1914 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001915 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001916 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001917 if (!VerifyOnly)
1918 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1919 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001920 ++Index;
1921 return true;
1922 }
1923
1924 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001925 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1926 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001928 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001929 DesignatedEndIndex = DesignatedStartIndex;
1930 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001931 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932
Mike Stump11289f42009-09-09 15:08:12 +00001933 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001934 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001935 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001936 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001937 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001938
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001939 // Codegen can't handle evaluating array range designators that have side
1940 // effects, because we replicate the AST value for each initialized element.
1941 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1942 // elements with something that has a side effect, so codegen can emit an
1943 // "error unsupported" error instead of miscompiling the app.
1944 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001945 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001946 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 }
1948
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001949 if (isa<ConstantArrayType>(AT)) {
1950 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001951 DesignatedStartIndex
1952 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001953 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001954 DesignatedEndIndex
1955 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001956 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1957 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001958 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001959 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1960 diag::err_array_designator_too_large)
1961 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1962 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001963 ++Index;
1964 return true;
1965 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001966 } else {
1967 // Make sure the bit-widths and signedness match.
1968 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001969 DesignatedEndIndex
1970 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001971 else if (DesignatedStartIndex.getBitWidth() <
1972 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001973 DesignatedStartIndex
1974 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001975 DesignatedStartIndex.setIsUnsigned(true);
1976 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001979 // Make sure that our non-designated initializer list has space
1980 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001981 if (!VerifyOnly &&
1982 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001983 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001984 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001985
Douglas Gregor17bd0942009-01-28 23:36:17 +00001986 // Repeatedly perform subobject initializations in the range
1987 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001988
Douglas Gregor17bd0942009-01-28 23:36:17 +00001989 // Move to the next designator
1990 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1991 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001993 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001994 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001995
Douglas Gregor17bd0942009-01-28 23:36:17 +00001996 while (DesignatedStartIndex <= DesignatedEndIndex) {
1997 // Recurse to check later designated subobjects.
1998 QualType ElementType = AT->getElementType();
1999 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002001 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2003 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002004 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002005 (DesignatedStartIndex == DesignatedEndIndex),
2006 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002007 return true;
2008
2009 // Move to the next index in the array that we'll be initializing.
2010 ++DesignatedStartIndex;
2011 ElementIndex = DesignatedStartIndex.getZExtValue();
2012 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002013
2014 // If this the first designator, our caller will continue checking
2015 // the rest of this array subobject.
2016 if (IsFirstDesignator) {
2017 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002018 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002019 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002020 return false;
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor17bd0942009-01-28 23:36:17 +00002023 if (!FinishSubobjectInit)
2024 return false;
2025
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002026 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002027 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002029 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002030 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002031 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002032}
2033
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002034// Get the structured initializer list for a subobject of type
2035// @p CurrentObjectType.
2036InitListExpr *
2037InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2038 QualType CurrentObjectType,
2039 InitListExpr *StructuredList,
2040 unsigned StructuredIndex,
2041 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002042 if (VerifyOnly)
2043 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002044 Expr *ExistingInit = 0;
2045 if (!StructuredList)
2046 ExistingInit = SyntacticToSemantic[IList];
2047 else if (StructuredIndex < StructuredList->getNumInits())
2048 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2051 return Result;
2052
2053 if (ExistingInit) {
2054 // We are creating an initializer list that initializes the
2055 // subobjects of the current object, but there was already an
2056 // initialization that completely initialized the current
2057 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002058 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002059 // struct X { int a, b; };
2060 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002061 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002062 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2063 // designated initializer re-initializes the whole
2064 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002065 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002066 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002067 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002068 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002069 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002070 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002071 << ExistingInit->getSourceRange();
2072 }
2073
Mike Stump11289f42009-09-09 15:08:12 +00002074 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002075 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2076 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002077 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002078
Douglas Gregora8a089b2010-07-13 18:40:04 +00002079 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002080
Douglas Gregor6d00c992009-03-20 23:58:33 +00002081 // Pre-allocate storage for the structured initializer list.
2082 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002083 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002084 bool GotNumInits = false;
2085 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002086 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002087 GotNumInits = true;
2088 } else if (Index < IList->getNumInits()) {
2089 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002090 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002091 GotNumInits = true;
2092 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002093 }
2094
Mike Stump11289f42009-09-09 15:08:12 +00002095 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002096 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2097 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2098 NumElements = CAType->getSize().getZExtValue();
2099 // Simple heuristic so that we don't allocate a very large
2100 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002101 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002102 NumElements = 0;
2103 }
John McCall9dd450b2009-09-21 23:43:11 +00002104 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002105 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002106 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002107 RecordDecl *RDecl = RType->getDecl();
2108 if (RDecl->isUnion())
2109 NumElements = 1;
2110 else
Mike Stump11289f42009-09-09 15:08:12 +00002111 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002112 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002113 }
2114
Ted Kremenekac034612010-04-13 23:39:13 +00002115 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002116
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002117 // Link this new initializer list into the structured initializer
2118 // lists.
2119 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002120 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 else {
2122 Result->setSyntacticForm(IList);
2123 SyntacticToSemantic[IList] = Result;
2124 }
2125
2126 return Result;
2127}
2128
2129/// Update the initializer at index @p StructuredIndex within the
2130/// structured initializer list to the value @p expr.
2131void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2132 unsigned &StructuredIndex,
2133 Expr *expr) {
2134 // No structured initializer list to update
2135 if (!StructuredList)
2136 return;
2137
Ted Kremenekac034612010-04-13 23:39:13 +00002138 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2139 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002141 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002142 diag::warn_initializer_overrides)
2143 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002144 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002146 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002147 << PrevInit->getSourceRange();
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002150 ++StructuredIndex;
2151}
2152
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002153/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002154/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002155/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002156/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002157/// failure. Returns the index expression, possibly with an implicit cast
2158/// added, on success. If everything went okay, Value will receive the
2159/// value of the constant expression.
2160static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002161CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002162 SourceLocation Loc = Index->getSourceRange().getBegin();
2163
2164 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002165 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2166 if (Result.isInvalid())
2167 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002168
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002169 if (Value.isSigned() && Value.isNegative())
2170 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 << Value.toString(10) << Index->getSourceRange();
2172
Douglas Gregor51650d32009-01-23 21:04:18 +00002173 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002174 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002175}
2176
John McCalldadc5752010-08-24 06:29:42 +00002177ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002178 SourceLocation Loc,
2179 bool GNUSyntax,
2180 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002181 typedef DesignatedInitExpr::Designator ASTDesignator;
2182
2183 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002184 SmallVector<ASTDesignator, 32> Designators;
2185 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002186
2187 // Build designators and check array designator expressions.
2188 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2189 const Designator &D = Desig.getDesignator(Idx);
2190 switch (D.getKind()) {
2191 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002192 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002193 D.getFieldLoc()));
2194 break;
2195
2196 case Designator::ArrayDesignator: {
2197 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2198 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002199 if (!Index->isTypeDependent() && !Index->isValueDependent())
2200 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2201 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002202 Invalid = true;
2203 else {
2204 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002205 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002206 D.getRBracketLoc()));
2207 InitExpressions.push_back(Index);
2208 }
2209 break;
2210 }
2211
2212 case Designator::ArrayRangeDesignator: {
2213 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2214 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2215 llvm::APSInt StartValue;
2216 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002217 bool StartDependent = StartIndex->isTypeDependent() ||
2218 StartIndex->isValueDependent();
2219 bool EndDependent = EndIndex->isTypeDependent() ||
2220 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002221 if (!StartDependent)
2222 StartIndex =
2223 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2224 if (!EndDependent)
2225 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2226
2227 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002228 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002229 else {
2230 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002231 if (StartDependent || EndDependent) {
2232 // Nothing to compute.
2233 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002234 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002236 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002237
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002238 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002239 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002240 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002241 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2242 Invalid = true;
2243 } else {
2244 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002245 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002246 D.getEllipsisLoc(),
2247 D.getRBracketLoc()));
2248 InitExpressions.push_back(StartIndex);
2249 InitExpressions.push_back(EndIndex);
2250 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002251 }
2252 break;
2253 }
2254 }
2255 }
2256
2257 if (Invalid || Init.isInvalid())
2258 return ExprError();
2259
2260 // Clear out the expressions within the designation.
2261 Desig.ClearExprs(*this);
2262
2263 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002264 = DesignatedInitExpr::Create(Context,
2265 Designators.data(), Designators.size(),
2266 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002267 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268
Richard Smithe4345902011-12-29 21:57:33 +00002269 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002270 Diag(DIE->getLocStart(), diag::ext_designated_init)
2271 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002273 return Owned(DIE);
2274}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002276//===----------------------------------------------------------------------===//
2277// Initialization entity
2278//===----------------------------------------------------------------------===//
2279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002281 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002283{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002284 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2285 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002286 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002287 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002288 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002289 Type = VT->getElementType();
2290 } else {
2291 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2292 assert(CT && "Unexpected type");
2293 Kind = EK_ComplexElement;
2294 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002295 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002296}
2297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002299 CXXBaseSpecifier *Base,
2300 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002301{
2302 InitializedEntity Result;
2303 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002304 Result.Base = reinterpret_cast<uintptr_t>(Base);
2305 if (IsInheritedVirtualBase)
2306 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor1b303932009-12-22 15:35:07 +00002308 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309 return Result;
2310}
2311
Douglas Gregor85dabae2009-12-16 01:38:02 +00002312DeclarationName InitializedEntity::getName() const {
2313 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002314 case EK_Parameter: {
2315 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2316 return (D ? D->getDeclName() : DeclarationName());
2317 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002318
2319 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002320 case EK_Member:
2321 return VariableOrMember->getDeclName();
2322
2323 case EK_Result:
2324 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002325 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002326 case EK_Temporary:
2327 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002328 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002329 case EK_ArrayElement:
2330 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002331 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002332 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002333 return DeclarationName();
2334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335
David Blaikie8a40f702012-01-17 06:56:22 +00002336 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002337}
2338
Douglas Gregora4b592a2009-12-19 03:01:41 +00002339DeclaratorDecl *InitializedEntity::getDecl() const {
2340 switch (getKind()) {
2341 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002342 case EK_Member:
2343 return VariableOrMember;
2344
John McCall31168b02011-06-15 23:02:42 +00002345 case EK_Parameter:
2346 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2347
Douglas Gregora4b592a2009-12-19 03:01:41 +00002348 case EK_Result:
2349 case EK_Exception:
2350 case EK_New:
2351 case EK_Temporary:
2352 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002353 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002354 case EK_ArrayElement:
2355 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002356 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002357 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002358 return 0;
2359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
David Blaikie8a40f702012-01-17 06:56:22 +00002361 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002362}
2363
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002364bool InitializedEntity::allowsNRVO() const {
2365 switch (getKind()) {
2366 case EK_Result:
2367 case EK_Exception:
2368 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002370 case EK_Variable:
2371 case EK_Parameter:
2372 case EK_Member:
2373 case EK_New:
2374 case EK_Temporary:
2375 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002376 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002377 case EK_ArrayElement:
2378 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002379 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002380 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002381 break;
2382 }
2383
2384 return false;
2385}
2386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002387//===----------------------------------------------------------------------===//
2388// Initialization sequence
2389//===----------------------------------------------------------------------===//
2390
2391void InitializationSequence::Step::Destroy() {
2392 switch (Kind) {
2393 case SK_ResolveAddressOfOverloadedFunction:
2394 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002395 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 case SK_CastDerivedToBaseLValue:
2397 case SK_BindReference:
2398 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002399 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 case SK_UserConversion:
2401 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002402 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002403 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002404 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002405 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002406 case SK_UnwrapInitList:
2407 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002408 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002409 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002410 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002411 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002412 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002413 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002414 case SK_PassByIndirectCopyRestore:
2415 case SK_PassByIndirectRestore:
2416 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002417 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 case SK_ConversionSequence:
2421 delete ICS;
2422 }
2423}
2424
Douglas Gregor838fcc32010-03-26 20:14:36 +00002425bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002426 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002427}
2428
2429bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002430 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002431 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432
Douglas Gregor838fcc32010-03-26 20:14:36 +00002433 switch (getFailureKind()) {
2434 case FK_TooManyInitsForReference:
2435 case FK_ArrayNeedsInitList:
2436 case FK_ArrayNeedsInitListOrStringLiteral:
2437 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2438 case FK_NonConstLValueReferenceBindingToTemporary:
2439 case FK_NonConstLValueReferenceBindingToUnrelated:
2440 case FK_RValueReferenceBindingToLValue:
2441 case FK_ReferenceInitDropsQualifiers:
2442 case FK_ReferenceInitFailed:
2443 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002444 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002445 case FK_TooManyInitsForScalar:
2446 case FK_ReferenceBindingToInitList:
2447 case FK_InitListBadDestinationType:
2448 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002449 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002450 case FK_ArrayTypeMismatch:
2451 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002452 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002453 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002454 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002455 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002456 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457
Douglas Gregor838fcc32010-03-26 20:14:36 +00002458 case FK_ReferenceInitOverloadFailed:
2459 case FK_UserConversionOverloadFailed:
2460 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002461 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002462 return FailedOverloadResult == OR_Ambiguous;
2463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
David Blaikie8a40f702012-01-17 06:56:22 +00002465 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002466}
2467
Douglas Gregorb33eed02010-04-16 22:09:46 +00002468bool InitializationSequence::isConstructorInitialization() const {
2469 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2470}
2471
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002472void
2473InitializationSequence
2474::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2475 DeclAccessPair Found,
2476 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Step S;
2478 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2479 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002480 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002481 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002482 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 Steps.push_back(S);
2484}
2485
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002487 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002489 switch (VK) {
2490 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2491 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2492 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002493 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494 S.Type = BaseType;
2495 Steps.push_back(S);
2496}
2497
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 bool BindingTemporary) {
2500 Step S;
2501 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2502 S.Type = T;
2503 Steps.push_back(S);
2504}
2505
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002506void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2507 Step S;
2508 S.Kind = SK_ExtraneousCopyToTemporary;
2509 S.Type = T;
2510 Steps.push_back(S);
2511}
2512
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002513void
2514InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2515 DeclAccessPair FoundDecl,
2516 QualType T,
2517 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 Step S;
2519 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002520 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002521 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002522 S.Function.Function = Function;
2523 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524 Steps.push_back(S);
2525}
2526
2527void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002528 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002529 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002530 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002531 switch (VK) {
2532 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002533 S.Kind = SK_QualificationConversionRValue;
2534 break;
John McCall2536c6d2010-08-25 10:28:54 +00002535 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002536 S.Kind = SK_QualificationConversionXValue;
2537 break;
John McCall2536c6d2010-08-25 10:28:54 +00002538 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539 S.Kind = SK_QualificationConversionLValue;
2540 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002541 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002542 S.Type = Ty;
2543 Steps.push_back(S);
2544}
2545
2546void InitializationSequence::AddConversionSequenceStep(
2547 const ImplicitConversionSequence &ICS,
2548 QualType T) {
2549 Step S;
2550 S.Kind = SK_ConversionSequence;
2551 S.Type = T;
2552 S.ICS = new ImplicitConversionSequence(ICS);
2553 Steps.push_back(S);
2554}
2555
Douglas Gregor51e77d52009-12-10 17:56:55 +00002556void InitializationSequence::AddListInitializationStep(QualType T) {
2557 Step S;
2558 S.Kind = SK_ListInitialization;
2559 S.Type = T;
2560 Steps.push_back(S);
2561}
2562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002564InitializationSequence
2565::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2566 AccessSpecifier Access,
2567 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002568 bool HadMultipleCandidates,
2569 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002570 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002571 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002572 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002573 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002574 S.Function.Function = Constructor;
2575 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002576 Steps.push_back(S);
2577}
2578
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002579void InitializationSequence::AddZeroInitializationStep(QualType T) {
2580 Step S;
2581 S.Kind = SK_ZeroInitialization;
2582 S.Type = T;
2583 Steps.push_back(S);
2584}
2585
Douglas Gregore1314a62009-12-18 05:02:21 +00002586void InitializationSequence::AddCAssignmentStep(QualType T) {
2587 Step S;
2588 S.Kind = SK_CAssignment;
2589 S.Type = T;
2590 Steps.push_back(S);
2591}
2592
Eli Friedman78275202009-12-19 08:11:05 +00002593void InitializationSequence::AddStringInitStep(QualType T) {
2594 Step S;
2595 S.Kind = SK_StringInit;
2596 S.Type = T;
2597 Steps.push_back(S);
2598}
2599
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002600void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2601 Step S;
2602 S.Kind = SK_ObjCObjectConversion;
2603 S.Type = T;
2604 Steps.push_back(S);
2605}
2606
Douglas Gregore2f943b2011-02-22 18:29:51 +00002607void InitializationSequence::AddArrayInitStep(QualType T) {
2608 Step S;
2609 S.Kind = SK_ArrayInit;
2610 S.Type = T;
2611 Steps.push_back(S);
2612}
2613
John McCall31168b02011-06-15 23:02:42 +00002614void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2615 bool shouldCopy) {
2616 Step s;
2617 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2618 : SK_PassByIndirectRestore);
2619 s.Type = type;
2620 Steps.push_back(s);
2621}
2622
2623void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2624 Step S;
2625 S.Kind = SK_ProduceObjCObject;
2626 S.Type = T;
2627 Steps.push_back(S);
2628}
2629
Sebastian Redlc1839b12012-01-17 22:49:42 +00002630void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2631 Step S;
2632 S.Kind = SK_StdInitializerList;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
Sebastian Redl29526f02011-11-27 16:50:07 +00002637void InitializationSequence::RewrapReferenceInitList(QualType T,
2638 InitListExpr *Syntactic) {
2639 assert(Syntactic->getNumInits() == 1 &&
2640 "Can only rewrap trivial init lists.");
2641 Step S;
2642 S.Kind = SK_UnwrapInitList;
2643 S.Type = Syntactic->getInit(0)->getType();
2644 Steps.insert(Steps.begin(), S);
2645
2646 S.Kind = SK_RewrapInitList;
2647 S.Type = T;
2648 S.WrappingSyntacticList = Syntactic;
2649 Steps.push_back(S);
2650}
2651
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002652void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002654 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002655 this->Failure = Failure;
2656 this->FailedOverloadResult = Result;
2657}
2658
2659//===----------------------------------------------------------------------===//
2660// Attempt initialization
2661//===----------------------------------------------------------------------===//
2662
John McCall31168b02011-06-15 23:02:42 +00002663static void MaybeProduceObjCObject(Sema &S,
2664 InitializationSequence &Sequence,
2665 const InitializedEntity &Entity) {
2666 if (!S.getLangOptions().ObjCAutoRefCount) return;
2667
2668 /// When initializing a parameter, produce the value if it's marked
2669 /// __attribute__((ns_consumed)).
2670 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2671 if (!Entity.isParameterConsumed())
2672 return;
2673
2674 assert(Entity.getType()->isObjCRetainableType() &&
2675 "consuming an object of unretainable type?");
2676 Sequence.AddProduceObjCObjectStep(Entity.getType());
2677
2678 /// When initializing a return value, if the return type is a
2679 /// retainable type, then returns need to immediately retain the
2680 /// object. If an autorelease is required, it will be done at the
2681 /// last instant.
2682 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2683 if (!Entity.getType()->isObjCRetainableType())
2684 return;
2685
2686 Sequence.AddProduceObjCObjectStep(Entity.getType());
2687 }
2688}
2689
Sebastian Redled2e5322011-12-22 14:44:04 +00002690/// \brief When initializing from init list via constructor, deal with the
2691/// empty init list and std::initializer_list special cases.
2692///
2693/// \return True if this was a special case, false otherwise.
2694static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002695 InitListExpr *List,
Sebastian Redled2e5322011-12-22 14:44:04 +00002696 CXXRecordDecl *DestRecordDecl,
2697 QualType DestType,
2698 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002699 // C++11 [dcl.init.list]p3:
Sebastian Redled2e5322011-12-22 14:44:04 +00002700 // List-initialization of an object of type T is defined as follows:
2701 // - If the initializer list has no elements and T is a class type with
2702 // a default constructor, the object is value-initialized.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002703 if (List->getNumInits() == 0) {
Sebastian Redled2e5322011-12-22 14:44:04 +00002704 if (CXXConstructorDecl *DefaultConstructor =
2705 S.LookupDefaultConstructor(DestRecordDecl)) {
2706 if (DefaultConstructor->isDeleted() ||
2707 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2708 // Fake an overload resolution failure.
2709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2710 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2711 DefaultConstructor->getAccess());
2712 if (FunctionTemplateDecl *ConstructorTmpl =
2713 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2714 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2715 /*ExplicitArgs*/ 0,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002716 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002717 /*SuppressUserConversions*/ false);
2718 else
2719 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002720 0, 0, CandidateSet,
Sebastian Redled2e5322011-12-22 14:44:04 +00002721 /*SuppressUserConversions*/ false);
2722 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002723 InitializationSequence::FK_ListConstructorOverloadFailed,
2724 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002725 } else
2726 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2727 DefaultConstructor->getAccess(),
2728 DestType,
2729 /*MultipleCandidates=*/false,
2730 /*FromInitList=*/true);
2731 return true;
2732 }
2733 }
2734
2735 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002736 QualType E;
2737 if (S.isStdInitializerList(DestType, &E)) {
2738 // Check that each individual element can be copy-constructed. But since we
2739 // have no place to store further information, we'll recalculate everything
2740 // later.
2741 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2742 S.Context.getConstantArrayType(E,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002743 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2744 List->getNumInits()),
Sebastian Redlc1839b12012-01-17 22:49:42 +00002745 ArrayType::Normal, 0));
2746 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2747 0, HiddenArray);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002748 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002749 Element.setElementIndex(i);
Sebastian Redl88e4d492012-02-04 21:27:33 +00002750 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002751 Sequence.SetFailed(
2752 InitializationSequence::FK_InitListElementCopyFailure);
2753 return true;
2754 }
2755 }
2756 Sequence.AddStdInitializerListConstructionStep(DestType);
2757 return true;
2758 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002759
2760 // Not a special case.
2761 return false;
2762}
2763
2764/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2765/// enumerates the constructors of the initialized entity and performs overload
2766/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002767/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00002768/// class type.
2769static void TryConstructorInitialization(Sema &S,
2770 const InitializedEntity &Entity,
2771 const InitializationKind &Kind,
2772 Expr **Args, unsigned NumArgs,
2773 QualType DestType,
2774 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002775 bool InitListSyntax = false) {
2776 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2777 "InitListSyntax must come with a single initializer list argument.");
2778
Sebastian Redled2e5322011-12-22 14:44:04 +00002779 // Check constructor arguments for self reference.
2780 if (DeclaratorDecl *DD = Entity.getDecl())
2781 // Parameters arguments are occassionially constructed with itself,
2782 // for instance, in recursive functions. Skip them.
2783 if (!isa<ParmVarDecl>(DD))
2784 for (unsigned i = 0; i < NumArgs; ++i)
2785 S.CheckSelfReference(DD, Args[i]);
2786
2787 // Build the candidate set directly in the initialization sequence
2788 // structure, so that it will persist if we fail.
2789 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2790 CandidateSet.clear();
2791
2792 // Determine whether we are allowed to call explicit constructors or
2793 // explicit conversion operators.
2794 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2795 Kind.getKind() == InitializationKind::IK_Value ||
2796 Kind.getKind() == InitializationKind::IK_Default);
2797
2798 // The type we're constructing needs to be complete.
2799 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2800 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2801 }
2802
2803 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2804 assert(DestRecordType && "Constructor initialization requires record type");
2805 CXXRecordDecl *DestRecordDecl
2806 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2807
Sebastian Redl88e4d492012-02-04 21:27:33 +00002808 if (InitListSyntax &&
2809 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2810 DestRecordDecl, DestType, Sequence))
Sebastian Redled2e5322011-12-22 14:44:04 +00002811 return;
2812
Sebastian Redl88e4d492012-02-04 21:27:33 +00002813 if (InitListSyntax) {
2814 // Time to unwrap the init list.
2815 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2816 Args = ILE->getInits();
2817 NumArgs = ILE->getNumInits();
2818 }
2819
Sebastian Redled2e5322011-12-22 14:44:04 +00002820 // - Otherwise, if T is a class type, constructors are considered. The
2821 // applicable constructors are enumerated, and the best one is chosen
2822 // through overload resolution.
2823 DeclContext::lookup_iterator Con, ConEnd;
2824 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2825 Con != ConEnd; ++Con) {
2826 NamedDecl *D = *Con;
2827 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2828 bool SuppressUserConversions = false;
2829
2830 // Find the constructor (which may be a template).
2831 CXXConstructorDecl *Constructor = 0;
2832 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2833 if (ConstructorTmpl)
2834 Constructor = cast<CXXConstructorDecl>(
2835 ConstructorTmpl->getTemplatedDecl());
2836 else {
2837 Constructor = cast<CXXConstructorDecl>(D);
2838
2839 // If we're performing copy initialization using a copy constructor, we
2840 // suppress user-defined conversions on the arguments.
2841 // FIXME: Move constructors?
2842 if (Kind.getKind() == InitializationKind::IK_Copy &&
2843 Constructor->isCopyConstructor())
2844 SuppressUserConversions = true;
2845 }
2846
2847 if (!Constructor->isInvalidDecl() &&
2848 (AllowExplicit || !Constructor->isExplicit())) {
2849 if (ConstructorTmpl)
2850 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2851 /*ExplicitArgs*/ 0,
2852 Args, NumArgs, CandidateSet,
2853 SuppressUserConversions);
2854 else
2855 S.AddOverloadCandidate(Constructor, FoundDecl,
2856 Args, NumArgs, CandidateSet,
2857 SuppressUserConversions);
2858 }
2859 }
2860
2861 SourceLocation DeclLoc = Kind.getLocation();
2862
2863 // Perform overload resolution. If it fails, return the failed result.
2864 OverloadCandidateSet::iterator Best;
2865 if (OverloadingResult Result
2866 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00002867 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002868 InitializationSequence::FK_ListConstructorOverloadFailed :
2869 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002870 Result);
2871 return;
2872 }
2873
2874 // C++0x [dcl.init]p6:
2875 // If a program calls for the default initialization of an object
2876 // of a const-qualified type T, T shall be a class type with a
2877 // user-provided default constructor.
2878 if (Kind.getKind() == InitializationKind::IK_Default &&
2879 Entity.getType().isConstQualified() &&
2880 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2881 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2882 return;
2883 }
2884
2885 // Add the constructor initialization step. Any cv-qualification conversion is
2886 // subsumed by the initialization.
2887 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2888 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2889 Sequence.AddConstructorInitializationStep(CtorDecl,
2890 Best->FoundDecl.getAccess(),
2891 DestType, HadMultipleCandidates,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002892 InitListSyntax);
Sebastian Redled2e5322011-12-22 14:44:04 +00002893}
2894
Sebastian Redl29526f02011-11-27 16:50:07 +00002895static bool
2896ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2897 Expr *Initializer,
2898 QualType &SourceType,
2899 QualType &UnqualifiedSourceType,
2900 QualType UnqualifiedTargetType,
2901 InitializationSequence &Sequence) {
2902 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2903 S.Context.OverloadTy) {
2904 DeclAccessPair Found;
2905 bool HadMultipleCandidates = false;
2906 if (FunctionDecl *Fn
2907 = S.ResolveAddressOfOverloadedFunction(Initializer,
2908 UnqualifiedTargetType,
2909 false, Found,
2910 &HadMultipleCandidates)) {
2911 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2912 HadMultipleCandidates);
2913 SourceType = Fn->getType();
2914 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2915 } else if (!UnqualifiedTargetType->isRecordType()) {
2916 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2917 return true;
2918 }
2919 }
2920 return false;
2921}
2922
2923static void TryReferenceInitializationCore(Sema &S,
2924 const InitializedEntity &Entity,
2925 const InitializationKind &Kind,
2926 Expr *Initializer,
2927 QualType cv1T1, QualType T1,
2928 Qualifiers T1Quals,
2929 QualType cv2T2, QualType T2,
2930 Qualifiers T2Quals,
2931 InitializationSequence &Sequence);
2932
2933static void TryListInitialization(Sema &S,
2934 const InitializedEntity &Entity,
2935 const InitializationKind &Kind,
2936 InitListExpr *InitList,
2937 InitializationSequence &Sequence);
2938
2939/// \brief Attempt list initialization of a reference.
2940static void TryReferenceListInitialization(Sema &S,
2941 const InitializedEntity &Entity,
2942 const InitializationKind &Kind,
2943 InitListExpr *InitList,
2944 InitializationSequence &Sequence)
2945{
2946 // First, catch C++03 where this isn't possible.
2947 if (!S.getLangOptions().CPlusPlus0x) {
2948 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2949 return;
2950 }
2951
2952 QualType DestType = Entity.getType();
2953 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2954 Qualifiers T1Quals;
2955 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2956
2957 // Reference initialization via an initializer list works thus:
2958 // If the initializer list consists of a single element that is
2959 // reference-related to the referenced type, bind directly to that element
2960 // (possibly creating temporaries).
2961 // Otherwise, initialize a temporary with the initializer list and
2962 // bind to that.
2963 if (InitList->getNumInits() == 1) {
2964 Expr *Initializer = InitList->getInit(0);
2965 QualType cv2T2 = Initializer->getType();
2966 Qualifiers T2Quals;
2967 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2968
2969 // If this fails, creating a temporary wouldn't work either.
2970 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
2971 T1, Sequence))
2972 return;
2973
2974 SourceLocation DeclLoc = Initializer->getLocStart();
2975 bool dummy1, dummy2, dummy3;
2976 Sema::ReferenceCompareResult RefRelationship
2977 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
2978 dummy2, dummy3);
2979 if (RefRelationship >= Sema::Ref_Related) {
2980 // Try to bind the reference here.
2981 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
2982 T1Quals, cv2T2, T2, T2Quals, Sequence);
2983 if (Sequence)
2984 Sequence.RewrapReferenceInitList(cv1T1, InitList);
2985 return;
2986 }
2987 }
2988
2989 // Not reference-related. Create a temporary and bind to that.
2990 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2991
2992 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
2993 if (Sequence) {
2994 if (DestType->isRValueReferenceType() ||
2995 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
2996 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2997 else
2998 Sequence.SetFailed(
2999 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3000 }
3001}
3002
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003003/// \brief Attempt list initialization (C++0x [dcl.init.list])
3004static void TryListInitialization(Sema &S,
3005 const InitializedEntity &Entity,
3006 const InitializationKind &Kind,
3007 InitListExpr *InitList,
3008 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003009 QualType DestType = Entity.getType();
3010
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003011 // C++ doesn't allow scalar initialization with more than one argument.
3012 // But C99 complex numbers are scalars and it makes sense there.
3013 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3014 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3015 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3016 return;
3017 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003018 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003019 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003020 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003021 }
3022 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003023 if (S.getLangOptions().CPlusPlus0x) {
3024 Expr *Arg = InitList;
3025 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3026 Sequence, /*InitListSyntax=*/true);
3027 } else
Sebastian Redled2e5322011-12-22 14:44:04 +00003028 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003029 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003030 }
3031
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003032 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003033 DestType, /*VerifyOnly=*/true,
3034 Kind.getKind() != InitializationKind::IK_Direct ||
3035 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003036 if (CheckInitList.HadError()) {
3037 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3038 return;
3039 }
3040
3041 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003042 Sequence.AddListInitializationStep(DestType);
3043}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003044
3045/// \brief Try a reference initialization that involves calling a conversion
3046/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003047static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3048 const InitializedEntity &Entity,
3049 const InitializationKind &Kind,
3050 Expr *Initializer,
3051 bool AllowRValues,
3052 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003053 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003054 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3055 QualType T1 = cv1T1.getUnqualifiedType();
3056 QualType cv2T2 = Initializer->getType();
3057 QualType T2 = cv2T2.getUnqualifiedType();
3058
3059 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003060 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003061 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003063 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003064 ObjCConversion,
3065 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003066 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003067 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003068 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003069 (void)ObjCLifetimeConversion;
3070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003071 // Build the candidate set directly in the initialization sequence
3072 // structure, so that it will persist if we fail.
3073 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3074 CandidateSet.clear();
3075
3076 // Determine whether we are allowed to call explicit constructors or
3077 // explicit conversion operators.
3078 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003080 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003081 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3082 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003083 // The type we're converting to is a class type. Enumerate its constructors
3084 // to see if there is a suitable conversion.
3085 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003086
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003087 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003088 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003089 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003090 NamedDecl *D = *Con;
3091 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3092
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003093 // Find the constructor (which may be a template).
3094 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003095 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003096 if (ConstructorTmpl)
3097 Constructor = cast<CXXConstructorDecl>(
3098 ConstructorTmpl->getTemplatedDecl());
3099 else
John McCalla0296f72010-03-19 07:35:19 +00003100 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003102 if (!Constructor->isInvalidDecl() &&
3103 Constructor->isConvertingConstructor(AllowExplicit)) {
3104 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003105 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003106 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003107 &Initializer, 1, CandidateSet,
3108 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003109 else
John McCalla0296f72010-03-19 07:35:19 +00003110 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003111 &Initializer, 1, CandidateSet,
3112 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003115 }
John McCall3696dcb2010-08-17 07:23:57 +00003116 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3117 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118
Douglas Gregor496e8b342010-05-07 19:42:26 +00003119 const RecordType *T2RecordType = 0;
3120 if ((T2RecordType = T2->getAs<RecordType>()) &&
3121 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122 // The type we're converting from is a class type, enumerate its conversion
3123 // functions.
3124 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3125
John McCallad371252010-01-20 00:46:10 +00003126 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003127 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003128 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3129 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130 NamedDecl *D = *I;
3131 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3132 if (isa<UsingShadowDecl>(D))
3133 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3136 CXXConversionDecl *Conv;
3137 if (ConvTemplate)
3138 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3139 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003140 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 // If the conversion function doesn't return a reference type,
3143 // it can't be considered for this conversion unless we're allowed to
3144 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145 // FIXME: Do we need to make sure that we only consider conversion
3146 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003147 // break recursion.
3148 if ((AllowExplicit || !Conv->isExplicit()) &&
3149 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3150 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003151 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003152 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003153 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003154 else
John McCalla0296f72010-03-19 07:35:19 +00003155 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003156 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003157 }
3158 }
3159 }
John McCall3696dcb2010-08-17 07:23:57 +00003160 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3161 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003162
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003163 SourceLocation DeclLoc = Initializer->getLocStart();
3164
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003168 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003169 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003170
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003172
Chandler Carruth30141632011-02-25 19:41:05 +00003173 // This is the overload that will actually be used for the initialization, so
3174 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003175 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003176
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003177 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003178 if (isa<CXXConversionDecl>(Function))
3179 T2 = Function->getResultType();
3180 else
3181 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003182
3183 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003184 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003185 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003186 T2.getNonLValueExprType(S.Context),
3187 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003188
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003190 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003191 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003192 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003193 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003194 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003195 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003198 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003199 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003202 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003203 NewDerivedToBase, NewObjCConversion,
3204 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003205 if (NewRefRelationship == Sema::Ref_Incompatible) {
3206 // If the type we've converted to is not reference-related to the
3207 // type we're looking for, then there is another conversion step
3208 // we need to perform to produce a temporary of the right type
3209 // that we'll be binding to.
3210 ImplicitConversionSequence ICS;
3211 ICS.setStandard();
3212 ICS.Standard = Best->FinalConversion;
3213 T2 = ICS.Standard.getToType(2);
3214 Sequence.AddConversionSequenceStep(ICS, T2);
3215 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216 Sequence.AddDerivedToBaseCastStep(
3217 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003218 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003219 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003220 else if (NewObjCConversion)
3221 Sequence.AddObjCObjectConversionStep(
3222 S.Context.getQualifiedType(T1,
3223 T2.getNonReferenceType().getQualifiers()));
3224
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003225 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003226 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003227
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3229 return OR_Success;
3230}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231
Richard Smithc620f552011-10-19 16:55:56 +00003232static void CheckCXX98CompatAccessibleCopy(Sema &S,
3233 const InitializedEntity &Entity,
3234 Expr *CurInitExpr);
3235
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3237static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 const InitializedEntity &Entity,
3239 const InitializationKind &Kind,
3240 Expr *Initializer,
3241 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003242 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003244 Qualifiers T1Quals;
3245 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003246 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003247 Qualifiers T2Quals;
3248 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 // If the initializer is the address of an overloaded function, try
3251 // to resolve the overloaded function. If all goes well, T2 is the
3252 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003253 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3254 T1, Sequence))
3255 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003256
Sebastian Redl29526f02011-11-27 16:50:07 +00003257 // Delegate everything else to a subfunction.
3258 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3259 T1Quals, cv2T2, T2, T2Quals, Sequence);
3260}
3261
3262/// \brief Reference initialization without resolving overloaded functions.
3263static void TryReferenceInitializationCore(Sema &S,
3264 const InitializedEntity &Entity,
3265 const InitializationKind &Kind,
3266 Expr *Initializer,
3267 QualType cv1T1, QualType T1,
3268 Qualifiers T1Quals,
3269 QualType cv2T2, QualType T2,
3270 Qualifiers T2Quals,
3271 InitializationSequence &Sequence) {
3272 QualType DestType = Entity.getType();
3273 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 // Compute some basic properties of the types and the initializer.
3275 bool isLValueRef = DestType->isLValueReferenceType();
3276 bool isRValueRef = !isLValueRef;
3277 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003278 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003279 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003280 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003281 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003282 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003283 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003285 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003287 // "cv2 T2" as follows:
3288 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003290 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003291 // Note the analogous bullet points for rvlaue refs to functions. Because
3292 // there are no function rvalues in C++, rvalue refs to functions are treated
3293 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003294 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003295 bool T1Function = T1->isFunctionType();
3296 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003298 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003300 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003302 // reference-compatible with "cv2 T2," or
3303 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003305 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003306 // can occur. However, we do pay attention to whether it is a bit-field
3307 // to decide whether we're actually binding to a temporary created from
3308 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003309 if (DerivedToBase)
3310 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003311 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003312 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003313 else if (ObjCConversion)
3314 Sequence.AddObjCObjectConversionStep(
3315 S.Context.getQualifiedType(T1, T2Quals));
3316
Chandler Carruth04bdce62010-01-12 20:32:25 +00003317 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003318 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003319 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003320 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003321 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003322 return;
3323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003324
3325 // - has a class type (i.e., T2 is a class type), where T1 is not
3326 // reference-related to T2, and can be implicitly converted to an
3327 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3328 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 // applicable conversion functions (13.3.1.6) and choosing the best
3330 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003331 // If we have an rvalue ref to function type here, the rhs must be
3332 // an rvalue.
3333 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3334 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003336 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003337 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003338 Sequence);
3339 if (ConvOvlResult == OR_Success)
3340 return;
John McCall0d1da222010-01-12 00:44:57 +00003341 if (ConvOvlResult != OR_No_Viable_Function) {
3342 Sequence.SetOverloadFailure(
3343 InitializationSequence::FK_ReferenceInitOverloadFailed,
3344 ConvOvlResult);
3345 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003346 }
3347 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003350 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003351 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003352 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003353 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3354 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3355 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003356 Sequence.SetOverloadFailure(
3357 InitializationSequence::FK_ReferenceInitOverloadFailed,
3358 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003359 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003360 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003361 ? (RefRelationship == Sema::Ref_Related
3362 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3363 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3364 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003365
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003366 return;
3367 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003368
Douglas Gregor92e460e2011-01-20 16:44:54 +00003369 // - If the initializer expression
3370 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3371 // "cv1 T1" is reference-compatible with "cv2 T2"
3372 // Note: functions are handled below.
3373 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003374 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003376 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003377 (InitCategory.isXValue() ||
3378 (InitCategory.isPRValue() && T2->isRecordType()) ||
3379 (InitCategory.isPRValue() && T2->isArrayType()))) {
3380 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3381 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003382 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3383 // compiler the freedom to perform a copy here or bind to the
3384 // object, while C++0x requires that we bind directly to the
3385 // object. Hence, we always bind to the object without making an
3386 // extra copy. However, in C++03 requires that we check for the
3387 // presence of a suitable copy constructor:
3388 //
3389 // The constructor that would be used to make the copy shall
3390 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003391 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003392 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003393 else if (S.getLangOptions().CPlusPlus0x)
3394 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396
Douglas Gregor92e460e2011-01-20 16:44:54 +00003397 if (DerivedToBase)
3398 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3399 ValueKind);
3400 else if (ObjCConversion)
3401 Sequence.AddObjCObjectConversionStep(
3402 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregor92e460e2011-01-20 16:44:54 +00003404 if (T1Quals != T2Quals)
3405 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003407 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
3411 // - has a class type (i.e., T2 is a class type), where T1 is not
3412 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003413 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3414 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003415 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003416 if (RefRelationship == Sema::Ref_Incompatible) {
3417 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3418 Kind, Initializer,
3419 /*AllowRValues=*/true,
3420 Sequence);
3421 if (ConvOvlResult)
3422 Sequence.SetOverloadFailure(
3423 InitializationSequence::FK_ReferenceInitOverloadFailed,
3424 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003426 return;
3427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003429 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3430 return;
3431 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003432
3433 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003434 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003436 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003437
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003438 // Determine whether we are allowed to call explicit constructors or
3439 // explicit conversion operators.
3440 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003441
3442 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3443
John McCall31168b02011-06-15 23:02:42 +00003444 ImplicitConversionSequence ICS
3445 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003446 /*SuppressUserConversions*/ false,
3447 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003448 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003449 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3450 /*AllowObjCWritebackConversion=*/false);
3451
3452 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003453 // FIXME: Use the conversion function set stored in ICS to turn
3454 // this into an overloading ambiguity diagnostic. However, we need
3455 // to keep that set as an OverloadCandidateSet rather than as some
3456 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003457 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3458 Sequence.SetOverloadFailure(
3459 InitializationSequence::FK_ReferenceInitOverloadFailed,
3460 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003461 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3462 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003463 else
3464 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003465 return;
John McCall31168b02011-06-15 23:02:42 +00003466 } else {
3467 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003468 }
3469
3470 // [...] If T1 is reference-related to T2, cv1 must be the
3471 // same cv-qualification as, or greater cv-qualification
3472 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003473 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3474 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003476 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003477 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3478 return;
3479 }
3480
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003482 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003484 InitCategory.isLValue()) {
3485 Sequence.SetFailed(
3486 InitializationSequence::FK_RValueReferenceBindingToLValue);
3487 return;
3488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003490 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3491 return;
3492}
3493
3494/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495/// (C++ [dcl.init.string], C99 6.7.8).
3496static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003497 const InitializedEntity &Entity,
3498 const InitializationKind &Kind,
3499 Expr *Initializer,
3500 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003501 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003502}
3503
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003504/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003506 const InitializedEntity &Entity,
3507 const InitializationKind &Kind,
3508 InitializationSequence &Sequence) {
3509 // C++ [dcl.init]p5:
3510 //
3511 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003512 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003514 // -- if T is an array type, then each element is value-initialized;
3515 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3516 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003518 if (const RecordType *RT = T->getAs<RecordType>()) {
3519 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3520 // -- if T is a class type (clause 9) with a user-declared
3521 // constructor (12.1), then the default constructor for T is
3522 // called (and the initialization is ill-formed if T has no
3523 // accessible default constructor);
3524 //
3525 // FIXME: we really want to refer to a single subobject of the array,
3526 // but Entity doesn't have a way to capture that (yet).
3527 if (ClassDecl->hasUserDeclaredConstructor())
3528 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003530 // -- if T is a (possibly cv-qualified) non-union class type
3531 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003532 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003533 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003534 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003535 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003536 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003538 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003539 }
3540 }
3541
Douglas Gregor1b303932009-12-22 15:35:07 +00003542 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003543}
3544
Douglas Gregor85dabae2009-12-16 01:38:02 +00003545/// \brief Attempt default initialization (C++ [dcl.init]p6).
3546static void TryDefaultInitialization(Sema &S,
3547 const InitializedEntity &Entity,
3548 const InitializationKind &Kind,
3549 InitializationSequence &Sequence) {
3550 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregor85dabae2009-12-16 01:38:02 +00003552 // C++ [dcl.init]p6:
3553 // To default-initialize an object of type T means:
3554 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003555 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3556
Douglas Gregor85dabae2009-12-16 01:38:02 +00003557 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3558 // constructor for T is called (and the initialization is ill-formed if
3559 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003560 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003561 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3562 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Douglas Gregor85dabae2009-12-16 01:38:02 +00003565 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregor85dabae2009-12-16 01:38:02 +00003567 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003569 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003570 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003571 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003572 return;
3573 }
3574
3575 // If the destination type has a lifetime property, zero-initialize it.
3576 if (DestType.getQualifiers().hasObjCLifetime()) {
3577 Sequence.AddZeroInitializationStep(Entity.getType());
3578 return;
3579 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003580}
3581
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3583/// which enumerates all conversion functions and performs overload resolution
3584/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003586 const InitializedEntity &Entity,
3587 const InitializationKind &Kind,
3588 Expr *Initializer,
3589 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003590 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003591 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3592 QualType SourceType = Initializer->getType();
3593 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3594 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595
Douglas Gregor540c3b02009-12-14 17:27:33 +00003596 // Build the candidate set directly in the initialization sequence
3597 // structure, so that it will persist if we fail.
3598 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3599 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregor540c3b02009-12-14 17:27:33 +00003601 // Determine whether we are allowed to call explicit constructors or
3602 // explicit conversion operators.
3603 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
Douglas Gregor540c3b02009-12-14 17:27:33 +00003605 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3606 // The type we're converting to is a class type. Enumerate its constructors
3607 // to see if there is a suitable conversion.
3608 CXXRecordDecl *DestRecordDecl
3609 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610
Douglas Gregord9848152010-04-26 14:36:57 +00003611 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003613 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003614 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003615 Con != ConEnd; ++Con) {
3616 NamedDecl *D = *Con;
3617 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Douglas Gregord9848152010-04-26 14:36:57 +00003619 // Find the constructor (which may be a template).
3620 CXXConstructorDecl *Constructor = 0;
3621 FunctionTemplateDecl *ConstructorTmpl
3622 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003623 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003624 Constructor = cast<CXXConstructorDecl>(
3625 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003626 else
Douglas Gregord9848152010-04-26 14:36:57 +00003627 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregord9848152010-04-26 14:36:57 +00003629 if (!Constructor->isInvalidDecl() &&
3630 Constructor->isConvertingConstructor(AllowExplicit)) {
3631 if (ConstructorTmpl)
3632 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3633 /*ExplicitArgs*/ 0,
3634 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003635 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003636 else
3637 S.AddOverloadCandidate(Constructor, FoundDecl,
3638 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003639 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003641 }
Douglas Gregord9848152010-04-26 14:36:57 +00003642 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003643 }
Eli Friedman78275202009-12-19 08:11:05 +00003644
3645 SourceLocation DeclLoc = Initializer->getLocStart();
3646
Douglas Gregor540c3b02009-12-14 17:27:33 +00003647 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3648 // The type we're converting from is a class type, enumerate its conversion
3649 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003650
Eli Friedman4afe9a32009-12-20 22:12:03 +00003651 // We can only enumerate the conversion functions for a complete type; if
3652 // the type isn't complete, simply skip this step.
3653 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3654 CXXRecordDecl *SourceRecordDecl
3655 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
John McCallad371252010-01-20 00:46:10 +00003657 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003658 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003659 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003661 I != E; ++I) {
3662 NamedDecl *D = *I;
3663 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3664 if (isa<UsingShadowDecl>(D))
3665 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666
Eli Friedman4afe9a32009-12-20 22:12:03 +00003667 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3668 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003669 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003670 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003671 else
John McCallda4458e2010-03-31 01:36:47 +00003672 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Eli Friedman4afe9a32009-12-20 22:12:03 +00003674 if (AllowExplicit || !Conv->isExplicit()) {
3675 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003676 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003677 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003678 CandidateSet);
3679 else
John McCalla0296f72010-03-19 07:35:19 +00003680 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003681 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003682 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003683 }
3684 }
3685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686
3687 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003688 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003689 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003690 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003691 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003692 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003693 Result);
3694 return;
3695 }
John McCall0d1da222010-01-12 00:44:57 +00003696
Douglas Gregor540c3b02009-12-14 17:27:33 +00003697 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003698 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003699 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Douglas Gregor540c3b02009-12-14 17:27:33 +00003701 if (isa<CXXConstructorDecl>(Function)) {
3702 // Add the user-defined conversion step. Any cv-qualification conversion is
3703 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003704 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3705 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003706 return;
3707 }
3708
3709 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003710 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003711 if (ConvType->getAs<RecordType>()) {
3712 // If we're converting to a class type, there may be an copy if
3713 // the resulting temporary object (possible to create an object of
3714 // a base class type). That copy is not a separate conversion, so
3715 // we just make a note of the actual destination type (possibly a
3716 // base class of the type returned by the conversion function) and
3717 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003718 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3719 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003720 return;
3721 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003722
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003723 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3724 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725
Douglas Gregor5ab11652010-04-17 22:01:05 +00003726 // If the conversion following the call to the conversion function
3727 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003728 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3729 Best->FinalConversion.Third) {
3730 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003731 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003732 ICS.Standard = Best->FinalConversion;
3733 Sequence.AddConversionSequenceStep(ICS, DestType);
3734 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735}
3736
John McCall31168b02011-06-15 23:02:42 +00003737/// The non-zero enum values here are indexes into diagnostic alternatives.
3738enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3739
3740/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003741static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3742 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003743 // Skip parens.
3744 e = e->IgnoreParens();
3745
3746 // Skip address-of nodes.
3747 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3748 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003749 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003750
3751 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003752 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3753 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003754 case CK_Dependent:
3755 case CK_BitCast:
3756 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003757 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003758 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003759
3760 case CK_ArrayToPointerDecay:
3761 return IIK_nonscalar;
3762
3763 case CK_NullToPointer:
3764 return IIK_okay;
3765
3766 default:
3767 break;
3768 }
3769
3770 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003771 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3772 if (!isAddressOf) return IIK_nonlocal;
3773
3774 VarDecl *var;
3775 if (isa<DeclRefExpr>(e)) {
3776 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3777 if (!var) return IIK_nonlocal;
3778 } else {
3779 var = cast<BlockDeclRefExpr>(e)->getDecl();
3780 }
3781
3782 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003783
3784 // If we have a conditional operator, check both sides.
3785 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003786 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003787 return iik;
3788
John McCall63f84442011-06-27 23:59:58 +00003789 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003790
3791 // These are never scalar.
3792 } else if (isa<ArraySubscriptExpr>(e)) {
3793 return IIK_nonscalar;
3794
3795 // Otherwise, it needs to be a null pointer constant.
3796 } else {
3797 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3798 ? IIK_okay : IIK_nonlocal);
3799 }
3800
3801 return IIK_nonlocal;
3802}
3803
3804/// Check whether the given expression is a valid operand for an
3805/// indirect copy/restore.
3806static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3807 assert(src->isRValue());
3808
John McCall63f84442011-06-27 23:59:58 +00003809 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003810 if (iik == IIK_okay) return;
3811
3812 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3813 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3814 << src->getSourceRange();
3815}
3816
Douglas Gregore2f943b2011-02-22 18:29:51 +00003817/// \brief Determine whether we have compatible array types for the
3818/// purposes of GNU by-copy array initialization.
3819static bool hasCompatibleArrayTypes(ASTContext &Context,
3820 const ArrayType *Dest,
3821 const ArrayType *Source) {
3822 // If the source and destination array types are equivalent, we're
3823 // done.
3824 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3825 return true;
3826
3827 // Make sure that the element types are the same.
3828 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3829 return false;
3830
3831 // The only mismatch we allow is when the destination is an
3832 // incomplete array type and the source is a constant array type.
3833 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3834}
3835
John McCall31168b02011-06-15 23:02:42 +00003836static bool tryObjCWritebackConversion(Sema &S,
3837 InitializationSequence &Sequence,
3838 const InitializedEntity &Entity,
3839 Expr *Initializer) {
3840 bool ArrayDecay = false;
3841 QualType ArgType = Initializer->getType();
3842 QualType ArgPointee;
3843 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3844 ArrayDecay = true;
3845 ArgPointee = ArgArrayType->getElementType();
3846 ArgType = S.Context.getPointerType(ArgPointee);
3847 }
3848
3849 // Handle write-back conversion.
3850 QualType ConvertedArgType;
3851 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3852 ConvertedArgType))
3853 return false;
3854
3855 // We should copy unless we're passing to an argument explicitly
3856 // marked 'out'.
3857 bool ShouldCopy = true;
3858 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3859 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3860
3861 // Do we need an lvalue conversion?
3862 if (ArrayDecay || Initializer->isGLValue()) {
3863 ImplicitConversionSequence ICS;
3864 ICS.setStandard();
3865 ICS.Standard.setAsIdentityConversion();
3866
3867 QualType ResultType;
3868 if (ArrayDecay) {
3869 ICS.Standard.First = ICK_Array_To_Pointer;
3870 ResultType = S.Context.getPointerType(ArgPointee);
3871 } else {
3872 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3873 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3874 }
3875
3876 Sequence.AddConversionSequenceStep(ICS, ResultType);
3877 }
3878
3879 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3880 return true;
3881}
3882
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003883InitializationSequence::InitializationSequence(Sema &S,
3884 const InitializedEntity &Entity,
3885 const InitializationKind &Kind,
3886 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003887 unsigned NumArgs)
3888 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003889 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003891 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003892 // The semantics of initializers are as follows. The destination type is
3893 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003894 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003896 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003897 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003898
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003899 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3901 SequenceKind = DependentSequence;
3902 return;
3903 }
3904
Sebastian Redld201edf2011-06-05 13:59:11 +00003905 // Almost everything is a normal sequence.
3906 setSequenceKind(NormalSequence);
3907
John McCalled75c092010-12-07 22:54:16 +00003908 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003909 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003910 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003911 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3912 if (result.isInvalid()) {
3913 SetFailed(FK_PlaceholderType);
3914 return;
John McCall4124c492011-10-17 18:40:02 +00003915 }
John McCalld5c98ae2011-11-15 01:35:18 +00003916 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00003917 }
John McCalled75c092010-12-07 22:54:16 +00003918
John McCall4124c492011-10-17 18:40:02 +00003919
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 QualType SourceType;
3921 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003922 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003923 Initializer = Args[0];
3924 if (!isa<InitListExpr>(Initializer))
3925 SourceType = Initializer->getType();
3926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
3928 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003929 // list-initialized (8.5.4).
3930 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003931 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003932 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003935 // - If the destination type is a reference type, see 8.5.3.
3936 if (DestType->isReferenceType()) {
3937 // C++0x [dcl.init.ref]p1:
3938 // A variable declared to be a T& or T&&, that is, "reference to type T"
3939 // (8.3.2), shall be initialized by an object, or function, of type T or
3940 // by an object that can be converted into a T.
3941 // (Therefore, multiple arguments are not permitted.)
3942 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003943 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003944 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003945 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003946 return;
3947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003949 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003950 if (Kind.getKind() == InitializationKind::IK_Value ||
3951 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003952 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003953 return;
3954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955
Douglas Gregor85dabae2009-12-16 01:38:02 +00003956 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003957 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003958 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003959 return;
3960 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003961
John McCall66884dd2011-02-21 07:22:22 +00003962 // - If the destination type is an array of characters, an array of
3963 // char16_t, an array of char32_t, or an array of wchar_t, and the
3964 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003966 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003967 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00003968 if (Initializer && isa<VariableArrayType>(DestAT)) {
3969 SetFailed(FK_VariableLengthArrayHasInitializer);
3970 return;
3971 }
3972
Douglas Gregore2f943b2011-02-22 18:29:51 +00003973 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003974 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003975 return;
3976 }
3977
Douglas Gregore2f943b2011-02-22 18:29:51 +00003978 // Note: as an GNU C extension, we allow initialization of an
3979 // array from a compound literal that creates an array of the same
3980 // type, so long as the initializer has no side effects.
3981 if (!S.getLangOptions().CPlusPlus && Initializer &&
3982 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3983 Initializer->getType()->isArrayType()) {
3984 const ArrayType *SourceAT
3985 = Context.getAsArrayType(Initializer->getType());
3986 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003987 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003988 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003989 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003990 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003991 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003992 }
3993 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003994 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003995 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003996 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003998 return;
3999 }
Eli Friedman78275202009-12-19 08:11:05 +00004000
John McCall31168b02011-06-15 23:02:42 +00004001 // Determine whether we should consider writeback conversions for
4002 // Objective-C ARC.
4003 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4004 Entity.getKind() == InitializedEntity::EK_Parameter;
4005
4006 // We're at the end of the line for C: it's either a write-back conversion
4007 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004008 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004009 // If allowed, check whether this is an Objective-C writeback conversion.
4010 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004011 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004012 return;
4013 }
4014
4015 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004016 AddCAssignmentStep(DestType);
4017 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004018 return;
4019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
John McCall31168b02011-06-15 23:02:42 +00004021 assert(S.getLangOptions().CPlusPlus);
4022
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004023 // - If the destination type is a (possibly cv-qualified) class type:
4024 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025 // - If the initialization is direct-initialization, or if it is
4026 // copy-initialization where the cv-unqualified version of the
4027 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004028 // class of the destination, constructors are considered. [...]
4029 if (Kind.getKind() == InitializationKind::IK_Direct ||
4030 (Kind.getKind() == InitializationKind::IK_Copy &&
4031 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4032 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004034 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004038 // used) to a derived class thereof are enumerated as described in
4039 // 13.3.1.4, and the best one is chosen through overload resolution
4040 // (13.3).
4041 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004042 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004043 return;
4044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045
Douglas Gregor85dabae2009-12-16 01:38:02 +00004046 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004047 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004048 return;
4049 }
4050 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051
4052 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004054 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004055 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4056 MaybeProduceObjCObject(S, *this, Entity);
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 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004061 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004062 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004065
4066 ImplicitConversionSequence ICS
4067 = S.TryImplicitConversion(Initializer, Entity.getType(),
4068 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004069 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004070 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004071 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4072 allowObjCWritebackConversion);
4073
4074 if (ICS.isStandard() &&
4075 ICS.Standard.Second == ICK_Writeback_Conversion) {
4076 // Objective-C ARC writeback conversion.
4077
4078 // We should copy unless we're passing to an argument explicitly
4079 // marked 'out'.
4080 bool ShouldCopy = true;
4081 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4082 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4083
4084 // If there was an lvalue adjustment, add it as a separate conversion.
4085 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4086 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4087 ImplicitConversionSequence LvalueICS;
4088 LvalueICS.setStandard();
4089 LvalueICS.Standard.setAsIdentityConversion();
4090 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4091 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004092 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004093 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004094
4095 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004096 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004097 DeclAccessPair dap;
4098 if (Initializer->getType() == Context.OverloadTy &&
4099 !S.ResolveAddressOfOverloadedFunction(Initializer
4100 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004101 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004102 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004103 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004104 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004105 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004106
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004107 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004108 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004109}
4110
4111InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004112 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004113 StepEnd = Steps.end();
4114 Step != StepEnd; ++Step)
4115 Step->Destroy();
4116}
4117
4118//===----------------------------------------------------------------------===//
4119// Perform initialization
4120//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004122getAssignmentAction(const InitializedEntity &Entity) {
4123 switch(Entity.getKind()) {
4124 case InitializedEntity::EK_Variable:
4125 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004126 case InitializedEntity::EK_Exception:
4127 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004128 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004129 return Sema::AA_Initializing;
4130
4131 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004133 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4134 return Sema::AA_Sending;
4135
Douglas Gregore1314a62009-12-18 05:02:21 +00004136 return Sema::AA_Passing;
4137
4138 case InitializedEntity::EK_Result:
4139 return Sema::AA_Returning;
4140
Douglas Gregore1314a62009-12-18 05:02:21 +00004141 case InitializedEntity::EK_Temporary:
4142 // FIXME: Can we tell apart casting vs. converting?
4143 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144
Douglas Gregore1314a62009-12-18 05:02:21 +00004145 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004146 case InitializedEntity::EK_ArrayElement:
4147 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004148 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004149 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004150 return Sema::AA_Initializing;
4151 }
4152
David Blaikie8a40f702012-01-17 06:56:22 +00004153 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004154}
4155
Douglas Gregor95562572010-04-24 23:45:46 +00004156/// \brief Whether we should binding a created object as a temporary when
4157/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004158static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004159 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004160 case InitializedEntity::EK_ArrayElement:
4161 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004162 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004163 case InitializedEntity::EK_New:
4164 case InitializedEntity::EK_Variable:
4165 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004166 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004167 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004168 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004169 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004170 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004171 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregore1314a62009-12-18 05:02:21 +00004173 case InitializedEntity::EK_Parameter:
4174 case InitializedEntity::EK_Temporary:
4175 return true;
4176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177
Douglas Gregore1314a62009-12-18 05:02:21 +00004178 llvm_unreachable("missed an InitializedEntity kind?");
4179}
4180
Douglas Gregor95562572010-04-24 23:45:46 +00004181/// \brief Whether the given entity, when initialized with an object
4182/// created for that initialization, requires destruction.
4183static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4184 switch (Entity.getKind()) {
4185 case InitializedEntity::EK_Member:
4186 case InitializedEntity::EK_Result:
4187 case InitializedEntity::EK_New:
4188 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004189 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004190 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004191 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004192 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004193 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
Douglas Gregor95562572010-04-24 23:45:46 +00004195 case InitializedEntity::EK_Variable:
4196 case InitializedEntity::EK_Parameter:
4197 case InitializedEntity::EK_Temporary:
4198 case InitializedEntity::EK_ArrayElement:
4199 case InitializedEntity::EK_Exception:
4200 return true;
4201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202
4203 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004204}
4205
Richard Smithc620f552011-10-19 16:55:56 +00004206/// \brief Look for copy and move constructors and constructor templates, for
4207/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4208static void LookupCopyAndMoveConstructors(Sema &S,
4209 OverloadCandidateSet &CandidateSet,
4210 CXXRecordDecl *Class,
4211 Expr *CurInitExpr) {
4212 DeclContext::lookup_iterator Con, ConEnd;
4213 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4214 Con != ConEnd; ++Con) {
4215 CXXConstructorDecl *Constructor = 0;
4216
4217 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4218 // Handle copy/moveconstructors, only.
4219 if (!Constructor || Constructor->isInvalidDecl() ||
4220 !Constructor->isCopyOrMoveConstructor() ||
4221 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4222 continue;
4223
4224 DeclAccessPair FoundDecl
4225 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4226 S.AddOverloadCandidate(Constructor, FoundDecl,
4227 &CurInitExpr, 1, CandidateSet);
4228 continue;
4229 }
4230
4231 // Handle constructor templates.
4232 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4233 if (ConstructorTmpl->isInvalidDecl())
4234 continue;
4235
4236 Constructor = cast<CXXConstructorDecl>(
4237 ConstructorTmpl->getTemplatedDecl());
4238 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4239 continue;
4240
4241 // FIXME: Do we need to limit this to copy-constructor-like
4242 // candidates?
4243 DeclAccessPair FoundDecl
4244 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4245 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4246 &CurInitExpr, 1, CandidateSet, true);
4247 }
4248}
4249
4250/// \brief Get the location at which initialization diagnostics should appear.
4251static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4252 Expr *Initializer) {
4253 switch (Entity.getKind()) {
4254 case InitializedEntity::EK_Result:
4255 return Entity.getReturnLoc();
4256
4257 case InitializedEntity::EK_Exception:
4258 return Entity.getThrowLoc();
4259
4260 case InitializedEntity::EK_Variable:
4261 return Entity.getDecl()->getLocation();
4262
4263 case InitializedEntity::EK_ArrayElement:
4264 case InitializedEntity::EK_Member:
4265 case InitializedEntity::EK_Parameter:
4266 case InitializedEntity::EK_Temporary:
4267 case InitializedEntity::EK_New:
4268 case InitializedEntity::EK_Base:
4269 case InitializedEntity::EK_Delegating:
4270 case InitializedEntity::EK_VectorElement:
4271 case InitializedEntity::EK_ComplexElement:
4272 case InitializedEntity::EK_BlockElement:
4273 return Initializer->getLocStart();
4274 }
4275 llvm_unreachable("missed an InitializedEntity kind?");
4276}
4277
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004278/// \brief Make a (potentially elidable) temporary copy of the object
4279/// provided by the given initializer by calling the appropriate copy
4280/// constructor.
4281///
4282/// \param S The Sema object used for type-checking.
4283///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004284/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004285/// the type of the initializer expression or a superclass thereof.
4286///
4287/// \param Enter The entity being initialized.
4288///
4289/// \param CurInit The initializer expression.
4290///
4291/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4292/// is permitted in C++03 (but not C++0x) when binding a reference to
4293/// an rvalue.
4294///
4295/// \returns An expression that copies the initializer expression into
4296/// a temporary object, or an error expression if a copy could not be
4297/// created.
John McCalldadc5752010-08-24 06:29:42 +00004298static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004299 QualType T,
4300 const InitializedEntity &Entity,
4301 ExprResult CurInit,
4302 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004303 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004304 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004306 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004307 Class = cast<CXXRecordDecl>(Record->getDecl());
4308 if (!Class)
4309 return move(CurInit);
4310
Douglas Gregor5d369002011-01-21 18:05:27 +00004311 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004312 // When certain criteria are met, an implementation is allowed to
4313 // omit the copy/move construction of a class object, even if the
4314 // copy/move constructor and/or destructor for the object have
4315 // side effects. [...]
4316 // - when a temporary class object that has not been bound to a
4317 // reference (12.2) would be copied/moved to a class object
4318 // with the same cv-unqualified type, the copy/move operation
4319 // can be omitted by constructing the temporary object
4320 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004322 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004323 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004325 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004326 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004327 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004328
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004330 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4331 return move(CurInit);
4332
Douglas Gregorf282a762011-01-21 19:38:21 +00004333 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004334 // Only consider constructors and constructor templates. Per
4335 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4336 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004337 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004338 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004340 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4341
Douglas Gregore1314a62009-12-18 05:02:21 +00004342 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004343 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004344 case OR_Success:
4345 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregore1314a62009-12-18 05:02:21 +00004347 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004348 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4349 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4350 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004351 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004352 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004353 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004354 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004355 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004356 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregore1314a62009-12-18 05:02:21 +00004358 case OR_Ambiguous:
4359 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004360 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004361 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004362 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004363 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
Douglas Gregore1314a62009-12-18 05:02:21 +00004365 case OR_Deleted:
4366 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004367 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004368 << CurInitExpr->getSourceRange();
4369 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004370 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004371 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004372 }
4373
Douglas Gregor5ab11652010-04-17 22:01:05 +00004374 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004375 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004376 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004377
Anders Carlssona01874b2010-04-21 18:47:17 +00004378 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004379 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004380
4381 if (IsExtraneousCopy) {
4382 // If this is a totally extraneous copy for C++03 reference
4383 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004384 // expression. We don't generate an (elided) copy operation here
4385 // because doing so would require us to pass down a flag to avoid
4386 // infinite recursion, where each step adds another extraneous,
4387 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004388
Douglas Gregor30b52772010-04-18 07:57:34 +00004389 // Instantiate the default arguments of any extra parameters in
4390 // the selected copy constructor, as if we were going to create a
4391 // proper call to the copy constructor.
4392 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4393 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4394 if (S.RequireCompleteType(Loc, Parm->getType(),
4395 S.PDiag(diag::err_call_incomplete_argument)))
4396 break;
4397
4398 // Build the default argument expression; we don't actually care
4399 // if this succeeds or not, because this routine will complain
4400 // if there was a problem.
4401 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4402 }
4403
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004404 return S.Owned(CurInitExpr);
4405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Eli Friedmanfa0df832012-02-02 03:46:19 +00004407 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004408
Douglas Gregor5ab11652010-04-17 22:01:05 +00004409 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004410 // constructor call (we might have derived-to-base conversions, or
4411 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004412 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004413 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004414 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004415
Douglas Gregord0ace022010-04-25 00:55:24 +00004416 // Actually perform the constructor call.
4417 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004418 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004419 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004420 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004421 CXXConstructExpr::CK_Complete,
4422 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregord0ace022010-04-25 00:55:24 +00004424 // If we're supposed to bind temporaries, do so.
4425 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4426 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4427 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004428}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004429
Richard Smithc620f552011-10-19 16:55:56 +00004430/// \brief Check whether elidable copy construction for binding a reference to
4431/// a temporary would have succeeded if we were building in C++98 mode, for
4432/// -Wc++98-compat.
4433static void CheckCXX98CompatAccessibleCopy(Sema &S,
4434 const InitializedEntity &Entity,
4435 Expr *CurInitExpr) {
4436 assert(S.getLangOptions().CPlusPlus0x);
4437
4438 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4439 if (!Record)
4440 return;
4441
4442 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4443 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4444 == DiagnosticsEngine::Ignored)
4445 return;
4446
4447 // Find constructors which would have been considered.
4448 OverloadCandidateSet CandidateSet(Loc);
4449 LookupCopyAndMoveConstructors(
4450 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4451
4452 // Perform overload resolution.
4453 OverloadCandidateSet::iterator Best;
4454 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4455
4456 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4457 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4458 << CurInitExpr->getSourceRange();
4459
4460 switch (OR) {
4461 case OR_Success:
4462 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4463 Best->FoundDecl.getAccess(), Diag);
4464 // FIXME: Check default arguments as far as that's possible.
4465 break;
4466
4467 case OR_No_Viable_Function:
4468 S.Diag(Loc, Diag);
4469 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4470 break;
4471
4472 case OR_Ambiguous:
4473 S.Diag(Loc, Diag);
4474 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4475 break;
4476
4477 case OR_Deleted:
4478 S.Diag(Loc, Diag);
4479 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4480 << 1 << Best->Function->isDeleted();
4481 break;
4482 }
4483}
4484
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004485void InitializationSequence::PrintInitLocationNote(Sema &S,
4486 const InitializedEntity &Entity) {
4487 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4488 if (Entity.getDecl()->getLocation().isInvalid())
4489 return;
4490
4491 if (Entity.getDecl()->getDeclName())
4492 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4493 << Entity.getDecl()->getDeclName();
4494 else
4495 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4496 }
4497}
4498
Sebastian Redl112aa822011-07-14 19:07:55 +00004499static bool isReferenceBinding(const InitializationSequence::Step &s) {
4500 return s.Kind == InitializationSequence::SK_BindReference ||
4501 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4502}
4503
Sebastian Redled2e5322011-12-22 14:44:04 +00004504static ExprResult
4505PerformConstructorInitialization(Sema &S,
4506 const InitializedEntity &Entity,
4507 const InitializationKind &Kind,
4508 MultiExprArg Args,
4509 const InitializationSequence::Step& Step,
4510 bool &ConstructorInitRequiresZeroInit) {
4511 unsigned NumArgs = Args.size();
4512 CXXConstructorDecl *Constructor
4513 = cast<CXXConstructorDecl>(Step.Function.Function);
4514 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4515
4516 // Build a call to the selected constructor.
4517 ASTOwningVector<Expr*> ConstructorArgs(S);
4518 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4519 ? Kind.getEqualLoc()
4520 : Kind.getLocation();
4521
4522 if (Kind.getKind() == InitializationKind::IK_Default) {
4523 // Force even a trivial, implicit default constructor to be
4524 // semantically checked. We do this explicitly because we don't build
4525 // the definition for completely trivial constructors.
4526 CXXRecordDecl *ClassDecl = Constructor->getParent();
4527 assert(ClassDecl && "No parent class for constructor.");
4528 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4529 ClassDecl->hasTrivialDefaultConstructor() &&
4530 !Constructor->isUsed(false))
4531 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4532 }
4533
4534 ExprResult CurInit = S.Owned((Expr *)0);
4535
4536 // Determine the arguments required to actually perform the constructor
4537 // call.
4538 if (S.CompleteConstructorCall(Constructor, move(Args),
4539 Loc, ConstructorArgs))
4540 return ExprError();
4541
4542
4543 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4544 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4545 (Kind.getKind() == InitializationKind::IK_Direct ||
4546 Kind.getKind() == InitializationKind::IK_Value)) {
4547 // An explicitly-constructed temporary, e.g., X(1, 2).
4548 unsigned NumExprs = ConstructorArgs.size();
4549 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004550 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004551 S.DiagnoseUseOfDecl(Constructor, Loc);
4552
4553 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4554 if (!TSInfo)
4555 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4556
4557 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4558 Constructor,
4559 TSInfo,
4560 Exprs,
4561 NumExprs,
4562 Kind.getParenRange(),
4563 HadMultipleCandidates,
4564 ConstructorInitRequiresZeroInit));
4565 } else {
4566 CXXConstructExpr::ConstructionKind ConstructKind =
4567 CXXConstructExpr::CK_Complete;
4568
4569 if (Entity.getKind() == InitializedEntity::EK_Base) {
4570 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4571 CXXConstructExpr::CK_VirtualBase :
4572 CXXConstructExpr::CK_NonVirtualBase;
4573 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4574 ConstructKind = CXXConstructExpr::CK_Delegating;
4575 }
4576
4577 // Only get the parenthesis range if it is a direct construction.
4578 SourceRange parenRange =
4579 Kind.getKind() == InitializationKind::IK_Direct ?
4580 Kind.getParenRange() : SourceRange();
4581
4582 // If the entity allows NRVO, mark the construction as elidable
4583 // unconditionally.
4584 if (Entity.allowsNRVO())
4585 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4586 Constructor, /*Elidable=*/true,
4587 move_arg(ConstructorArgs),
4588 HadMultipleCandidates,
4589 ConstructorInitRequiresZeroInit,
4590 ConstructKind,
4591 parenRange);
4592 else
4593 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4594 Constructor,
4595 move_arg(ConstructorArgs),
4596 HadMultipleCandidates,
4597 ConstructorInitRequiresZeroInit,
4598 ConstructKind,
4599 parenRange);
4600 }
4601 if (CurInit.isInvalid())
4602 return ExprError();
4603
4604 // Only check access if all of that succeeded.
4605 S.CheckConstructorAccess(Loc, Constructor, Entity,
4606 Step.Function.FoundDecl.getAccess());
4607 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4608
4609 if (shouldBindAsTemporary(Entity))
4610 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4611
4612 return move(CurInit);
4613}
4614
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004616InitializationSequence::Perform(Sema &S,
4617 const InitializedEntity &Entity,
4618 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004619 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004620 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004621 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004622 unsigned NumArgs = Args.size();
4623 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004624 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Sebastian Redld201edf2011-06-05 13:59:11 +00004627 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004628 // If the declaration is a non-dependent, incomplete array type
4629 // that has an initializer, then its type will be completed once
4630 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004631 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004632 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004633 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004634 if (const IncompleteArrayType *ArrayT
4635 = S.Context.getAsIncompleteArrayType(DeclType)) {
4636 // FIXME: We don't currently have the ability to accurately
4637 // compute the length of an initializer list without
4638 // performing full type-checking of the initializer list
4639 // (since we have to determine where braces are implicitly
4640 // introduced and such). So, we fall back to making the array
4641 // type a dependently-sized array type with no specified
4642 // bound.
4643 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4644 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004645
Douglas Gregor51e77d52009-12-10 17:56:55 +00004646 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004647 if (DeclaratorDecl *DD = Entity.getDecl()) {
4648 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4649 TypeLoc TL = TInfo->getTypeLoc();
4650 if (IncompleteArrayTypeLoc *ArrayLoc
4651 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4652 Brackets = ArrayLoc->getBracketsRange();
4653 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004654 }
4655
4656 *ResultType
4657 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4658 /*NumElts=*/0,
4659 ArrayT->getSizeModifier(),
4660 ArrayT->getIndexTypeCVRQualifiers(),
4661 Brackets);
4662 }
4663
4664 }
4665 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004666 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4667 Kind.isExplicitCast());
4668 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004669 }
4670
Sebastian Redld201edf2011-06-05 13:59:11 +00004671 // No steps means no initialization.
4672 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004673 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregor1b303932009-12-22 15:35:07 +00004675 QualType DestType = Entity.getType().getNonReferenceType();
4676 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004677 // the same as Entity.getDecl()->getType() in cases involving type merging,
4678 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004679 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004680 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004681 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004682
John McCalldadc5752010-08-24 06:29:42 +00004683 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004685 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004686 // grab the only argument out the Args and place it into the "current"
4687 // initializer.
4688 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004689 case SK_ResolveAddressOfOverloadedFunction:
4690 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004691 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004692 case SK_CastDerivedToBaseLValue:
4693 case SK_BindReference:
4694 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004695 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004696 case SK_UserConversion:
4697 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004698 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004699 case SK_QualificationConversionRValue:
4700 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004701 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004702 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004703 case SK_UnwrapInitList:
4704 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004705 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004706 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004707 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004708 case SK_ArrayInit:
4709 case SK_PassByIndirectCopyRestore:
4710 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004711 case SK_ProduceObjCObject:
4712 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004713 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004714 CurInit = Args.get()[0];
4715 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004716 break;
John McCall34376a62010-12-04 03:47:34 +00004717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004718
Douglas Gregore1314a62009-12-18 05:02:21 +00004719 case SK_ConstructorInitialization:
4720 case SK_ZeroInitialization:
4721 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
4724 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004725 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004726 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004727 for (step_iterator Step = step_begin(), StepEnd = step_end();
4728 Step != StepEnd; ++Step) {
4729 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004730 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
John Wiegley01296292011-04-08 18:41:53 +00004732 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004734 switch (Step->Kind) {
4735 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004736 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004737 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004738 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004739 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004740 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004741 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004742 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004745 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004746 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004747 case SK_CastDerivedToBaseLValue: {
4748 // We have a derived-to-base cast that produces either an rvalue or an
4749 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
John McCallcf142162010-08-07 06:22:56 +00004751 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004752
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004753 // Casts to inaccessible base classes are allowed with C-style casts.
4754 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4755 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004756 CurInit.get()->getLocStart(),
4757 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004758 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004759 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
Douglas Gregor88d292c2010-05-13 16:44:06 +00004761 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4762 QualType T = SourceType;
4763 if (const PointerType *Pointer = T->getAs<PointerType>())
4764 T = Pointer->getPointeeType();
4765 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004766 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004767 cast<CXXRecordDecl>(RecordTy->getDecl()));
4768 }
4769
John McCall2536c6d2010-08-25 10:28:54 +00004770 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004771 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004772 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004773 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004774 VK_XValue :
4775 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004776 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4777 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004778 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004779 CurInit.get(),
4780 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004781 break;
4782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004783
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004784 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004785 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004786 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4787 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004788 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004789 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004790 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004791 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004792 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004793 }
Anders Carlssona91be642010-01-29 02:47:33 +00004794
John Wiegley01296292011-04-08 18:41:53 +00004795 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004796 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004797 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4798 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004799 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004800 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004801 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004804 // Reference binding does not have any corresponding ASTs.
4805
4806 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004807 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004808 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004809
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004810 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004811
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004812 case SK_BindReferenceToTemporary:
4813 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004814 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004815 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004816
Douglas Gregorfe314812011-06-21 17:03:29 +00004817 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004818 CurInit = new (S.Context) MaterializeTemporaryExpr(
4819 Entity.getType().getNonReferenceType(),
4820 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004821 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004822
4823 // If we're binding to an Objective-C object that has lifetime, we
4824 // need cleanups.
4825 if (S.getLangOptions().ObjCAutoRefCount &&
4826 CurInit.get()->getType()->isObjCLifetimeType())
4827 S.ExprNeedsCleanups = true;
4828
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004829 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004831 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004833 /*IsExtraneousCopy=*/true);
4834 break;
4835
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004836 case SK_UserConversion: {
4837 // We have a user-defined conversion that invokes either a constructor
4838 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004839 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004840 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004841 FunctionDecl *Fn = Step->Function.Function;
4842 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004843 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004844 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004845 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004847 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004848 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004849 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004850
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004851 // Determine the arguments required to actually perform the constructor
4852 // call.
John Wiegley01296292011-04-08 18:41:53 +00004853 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004854 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004855 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004856 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004857 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004859 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004861 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004862 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004863 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004864 CXXConstructExpr::CK_Complete,
4865 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004867 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004868
Anders Carlssona01874b2010-04-21 18:47:17 +00004869 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004870 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004871 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
John McCalle3027922010-08-25 11:45:40 +00004873 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004874 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4875 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4876 S.IsDerivedFrom(SourceType, Class))
4877 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004878
Douglas Gregor95562572010-04-24 23:45:46 +00004879 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004880 } else {
4881 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004882 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004883 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004884 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004885 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
4887 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004888 // derived-to-base conversion? I believe the answer is "no", because
4889 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004890 ExprResult CurInitExprRes =
4891 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4892 FoundFn, Conversion);
4893 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004894 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004895 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004898 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4899 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004900 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004901 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902
John McCalle3027922010-08-25 11:45:40 +00004903 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004904
Douglas Gregor95562572010-04-24 23:45:46 +00004905 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004907
Sebastian Redl112aa822011-07-14 19:07:55 +00004908 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004909 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4910
4911 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004912 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004913 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004915 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004916 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004917 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004918 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00004919 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004920 }
4921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
John McCallcf142162010-08-07 06:22:56 +00004923 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004924 CurInit.get()->getType(),
4925 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004926 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004927 if (MaybeBindToTemp)
4928 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004929 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004930 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4931 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004932 break;
4933 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004934
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004935 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004936 case SK_QualificationConversionXValue:
4937 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004938 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004939 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004940 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004941 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004942 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004943 VK_XValue :
4944 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004945 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004946 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004947 }
4948
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004949 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004950 Sema::CheckedConversionKind CCK
4951 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4952 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00004953 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00004954 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004955 ExprResult CurInitExprRes =
4956 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004957 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004958 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004959 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004960 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004963
Douglas Gregor51e77d52009-12-10 17:56:55 +00004964 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004965 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00004966 // Hack: We must pass *ResultType if available in order to set the type
4967 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
4968 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
4969 // temporary, not a reference, so we should pass Ty.
4970 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
4971 // Since this step is never used for a reference directly, we explicitly
4972 // unwrap references here and rewrap them afterwards.
4973 // We also need to create a InitializeTemporary entity for this.
4974 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
4975 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
4976 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
4977 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
4978 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00004979 Kind.getKind() != InitializationKind::IK_Direct ||
4980 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004981 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004982 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004983
Sebastian Redl29526f02011-11-27 16:50:07 +00004984 if (ResultType) {
4985 if ((*ResultType)->isRValueReferenceType())
4986 Ty = S.Context.getRValueReferenceType(Ty);
4987 else if ((*ResultType)->isLValueReferenceType())
4988 Ty = S.Context.getLValueReferenceType(Ty,
4989 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
4990 *ResultType = Ty;
4991 }
4992
4993 InitListExpr *StructuredInitList =
4994 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004995 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00004996 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004997 break;
4998 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004999
Sebastian Redled2e5322011-12-22 14:44:04 +00005000 case SK_ListConstructorCall: {
5001 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5002 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5003 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5004 move(Arg), *Step,
5005 ConstructorInitRequiresZeroInit);
5006 break;
5007 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005008
Sebastian Redl29526f02011-11-27 16:50:07 +00005009 case SK_UnwrapInitList:
5010 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5011 break;
5012
5013 case SK_RewrapInitList: {
5014 Expr *E = CurInit.take();
5015 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5016 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5017 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5018 ILE->setSyntacticForm(Syntactic);
5019 ILE->setType(E->getType());
5020 ILE->setValueKind(E->getValueKind());
5021 CurInit = S.Owned(ILE);
5022 break;
5023 }
5024
Sebastian Redled2e5322011-12-22 14:44:04 +00005025 case SK_ConstructorInitialization:
5026 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5027 *Step,
5028 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005029 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005031 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005032 step_iterator NextStep = Step;
5033 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005034 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005035 NextStep->Kind == SK_ConstructorInitialization) {
5036 // The need for zero-initialization is recorded directly into
5037 // the call to the object's constructor within the next step.
5038 ConstructorInitRequiresZeroInit = true;
5039 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5040 S.getLangOptions().CPlusPlus &&
5041 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005042 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5043 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005045 Kind.getRange().getBegin());
5046
5047 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5048 TSInfo->getType().getNonLValueExprType(S.Context),
5049 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005050 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005051 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005052 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005053 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005054 break;
5055 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005056
5057 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005058 QualType SourceType = CurInit.get()->getType();
5059 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005060 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005061 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5062 if (Result.isInvalid())
5063 return ExprError();
5064 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005065
5066 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005067 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005068 if (ConvTy != Sema::Compatible &&
5069 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005070 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005071 == Sema::Compatible)
5072 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005073 if (CurInitExprRes.isInvalid())
5074 return ExprError();
5075 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005076
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005077 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005078 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5079 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005080 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005081 getAssignmentAction(Entity),
5082 &Complained)) {
5083 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005084 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005085 } else if (Complained)
5086 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005087 break;
5088 }
Eli Friedman78275202009-12-19 08:11:05 +00005089
5090 case SK_StringInit: {
5091 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005092 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005093 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005094 break;
5095 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005096
5097 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005098 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005099 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005100 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005101 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005102
5103 case SK_ArrayInit:
5104 // Okay: we checked everything before creating this step. Note that
5105 // this is a GNU extension.
5106 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005107 << Step->Type << CurInit.get()->getType()
5108 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005109
5110 // If the destination type is an incomplete array type, update the
5111 // type accordingly.
5112 if (ResultType) {
5113 if (const IncompleteArrayType *IncompleteDest
5114 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5115 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005116 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005117 *ResultType = S.Context.getConstantArrayType(
5118 IncompleteDest->getElementType(),
5119 ConstantSource->getSize(),
5120 ArrayType::Normal, 0);
5121 }
5122 }
5123 }
John McCall31168b02011-06-15 23:02:42 +00005124 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005125
John McCall31168b02011-06-15 23:02:42 +00005126 case SK_PassByIndirectCopyRestore:
5127 case SK_PassByIndirectRestore:
5128 checkIndirectCopyRestoreSource(S, CurInit.get());
5129 CurInit = S.Owned(new (S.Context)
5130 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5131 Step->Kind == SK_PassByIndirectCopyRestore));
5132 break;
5133
5134 case SK_ProduceObjCObject:
5135 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005136 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005137 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005138 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005139
5140 case SK_StdInitializerList: {
5141 QualType Dest = Step->Type;
5142 QualType E;
5143 bool Success = S.isStdInitializerList(Dest, &E);
5144 (void)Success;
5145 assert(Success && "Destination type changed?");
5146 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5147 unsigned NumInits = ILE->getNumInits();
5148 SmallVector<Expr*, 16> Converted(NumInits);
5149 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5150 S.Context.getConstantArrayType(E,
5151 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5152 NumInits),
5153 ArrayType::Normal, 0));
5154 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5155 0, HiddenArray);
5156 for (unsigned i = 0; i < NumInits; ++i) {
5157 Element.setElementIndex(i);
5158 ExprResult Init = S.Owned(ILE->getInit(i));
5159 ExprResult Res = S.PerformCopyInitialization(Element,
5160 Init.get()->getExprLoc(),
5161 Init);
5162 assert(!Res.isInvalid() && "Result changed since try phase.");
5163 Converted[i] = Res.take();
5164 }
5165 InitListExpr *Semantic = new (S.Context)
5166 InitListExpr(S.Context, ILE->getLBraceLoc(),
5167 Converted.data(), NumInits, ILE->getRBraceLoc());
5168 Semantic->setSyntacticForm(ILE);
5169 Semantic->setType(Dest);
5170 CurInit = S.Owned(Semantic);
5171 break;
5172 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005173 }
5174 }
John McCall1f425642010-11-11 03:21:53 +00005175
5176 // Diagnose non-fatal problems with the completed initialization.
5177 if (Entity.getKind() == InitializedEntity::EK_Member &&
5178 cast<FieldDecl>(Entity.getDecl())->isBitField())
5179 S.CheckBitFieldInitialization(Kind.getLocation(),
5180 cast<FieldDecl>(Entity.getDecl()),
5181 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005183 return move(CurInit);
5184}
5185
5186//===----------------------------------------------------------------------===//
5187// Diagnose initialization failures
5188//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005190 const InitializedEntity &Entity,
5191 const InitializationKind &Kind,
5192 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005193 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005194 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
Douglas Gregor1b303932009-12-22 15:35:07 +00005196 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005197 switch (Failure) {
5198 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005199 // FIXME: Customize for the initialized entity?
5200 if (NumArgs == 0)
5201 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5202 << DestType.getNonReferenceType();
5203 else // FIXME: diagnostic below could be better!
5204 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5205 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005206 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005208 case FK_ArrayNeedsInitList:
5209 case FK_ArrayNeedsInitListOrStringLiteral:
5210 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5211 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5212 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005213
Douglas Gregore2f943b2011-02-22 18:29:51 +00005214 case FK_ArrayTypeMismatch:
5215 case FK_NonConstantArrayInit:
5216 S.Diag(Kind.getLocation(),
5217 (Failure == FK_ArrayTypeMismatch
5218 ? diag::err_array_init_different_type
5219 : diag::err_array_init_non_constant_array))
5220 << DestType.getNonReferenceType()
5221 << Args[0]->getType()
5222 << Args[0]->getSourceRange();
5223 break;
5224
John McCalla59dc2f2012-01-05 00:13:19 +00005225 case FK_VariableLengthArrayHasInitializer:
5226 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5227 << Args[0]->getSourceRange();
5228 break;
5229
John McCall16df1e52010-03-30 21:47:33 +00005230 case FK_AddressOfOverloadFailed: {
5231 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005232 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005233 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005234 true,
5235 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005236 break;
John McCall16df1e52010-03-30 21:47:33 +00005237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005238
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005239 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005240 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005241 switch (FailedOverloadResult) {
5242 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005243 if (Failure == FK_UserConversionOverloadFailed)
5244 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5245 << Args[0]->getType() << DestType
5246 << Args[0]->getSourceRange();
5247 else
5248 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5249 << DestType << Args[0]->getType()
5250 << Args[0]->getSourceRange();
5251
John McCall5c32be02010-08-24 20:38:10 +00005252 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005253 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005254
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005255 case OR_No_Viable_Function:
5256 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5257 << Args[0]->getType() << DestType.getNonReferenceType()
5258 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005259 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005260 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005261
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005262 case OR_Deleted: {
5263 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5264 << Args[0]->getType() << DestType.getNonReferenceType()
5265 << Args[0]->getSourceRange();
5266 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005267 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005268 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5269 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005270 if (Ovl == OR_Deleted) {
5271 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005272 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005273 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005274 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005275 }
5276 break;
5277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005279 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005280 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005281 }
5282 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005284 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005285 if (isa<InitListExpr>(Args[0])) {
5286 S.Diag(Kind.getLocation(),
5287 diag::err_lvalue_reference_bind_to_initlist)
5288 << DestType.getNonReferenceType().isVolatileQualified()
5289 << DestType.getNonReferenceType()
5290 << Args[0]->getSourceRange();
5291 break;
5292 }
5293 // Intentional fallthrough
5294
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005295 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005296 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005297 Failure == FK_NonConstLValueReferenceBindingToTemporary
5298 ? diag::err_lvalue_reference_bind_to_temporary
5299 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005300 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005301 << DestType.getNonReferenceType()
5302 << Args[0]->getType()
5303 << Args[0]->getSourceRange();
5304 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005305
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005306 case FK_RValueReferenceBindingToLValue:
5307 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005308 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005309 << Args[0]->getSourceRange();
5310 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005312 case FK_ReferenceInitDropsQualifiers:
5313 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5314 << DestType.getNonReferenceType()
5315 << Args[0]->getType()
5316 << Args[0]->getSourceRange();
5317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005318
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005319 case FK_ReferenceInitFailed:
5320 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5321 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005322 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 << Args[0]->getType()
5324 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005325 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5326 Args[0]->getType()->isObjCObjectPointerType())
5327 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005328 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005329
Douglas Gregorb491ed32011-02-19 21:32:49 +00005330 case FK_ConversionFailed: {
5331 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005332 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005333 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005334 << DestType
John McCall086a4642010-11-24 05:12:34 +00005335 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005336 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005337 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005338 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5339 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005340 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5341 Args[0]->getType()->isObjCObjectPointerType())
5342 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005343 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005344 }
John Wiegley01296292011-04-08 18:41:53 +00005345
5346 case FK_ConversionFromPropertyFailed:
5347 // No-op. This error has already been reported.
5348 break;
5349
Douglas Gregor51e77d52009-12-10 17:56:55 +00005350 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005351 SourceRange R;
5352
5353 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005354 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005355 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005357 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005358
Douglas Gregor8ec51732010-09-08 21:40:08 +00005359 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5360 if (Kind.isCStyleOrFunctionalCast())
5361 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5362 << R;
5363 else
5364 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5365 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005366 break;
5367 }
5368
5369 case FK_ReferenceBindingToInitList:
5370 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5371 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5372 break;
5373
5374 case FK_InitListBadDestinationType:
5375 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5376 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5377 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005378
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005379 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005380 case FK_ConstructorOverloadFailed: {
5381 SourceRange ArgsRange;
5382 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005384 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005386 if (Failure == FK_ListConstructorOverloadFailed) {
5387 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5388 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5389 Args = InitList->getInits();
5390 NumArgs = InitList->getNumInits();
5391 }
5392
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005393 // FIXME: Using "DestType" for the entity we're printing is probably
5394 // bad.
5395 switch (FailedOverloadResult) {
5396 case OR_Ambiguous:
5397 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5398 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005399 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5400 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005401 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005402
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005403 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005404 if (Kind.getKind() == InitializationKind::IK_Default &&
5405 (Entity.getKind() == InitializedEntity::EK_Base ||
5406 Entity.getKind() == InitializedEntity::EK_Member) &&
5407 isa<CXXConstructorDecl>(S.CurContext)) {
5408 // This is implicit default initialization of a member or
5409 // base within a constructor. If no viable function was
5410 // found, notify the user that she needs to explicitly
5411 // initialize this base/member.
5412 CXXConstructorDecl *Constructor
5413 = cast<CXXConstructorDecl>(S.CurContext);
5414 if (Entity.getKind() == InitializedEntity::EK_Base) {
5415 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5416 << Constructor->isImplicit()
5417 << S.Context.getTypeDeclType(Constructor->getParent())
5418 << /*base=*/0
5419 << Entity.getType();
5420
5421 RecordDecl *BaseDecl
5422 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5423 ->getDecl();
5424 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5425 << S.Context.getTagDeclType(BaseDecl);
5426 } else {
5427 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5428 << Constructor->isImplicit()
5429 << S.Context.getTypeDeclType(Constructor->getParent())
5430 << /*member=*/1
5431 << Entity.getName();
5432 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5433
5434 if (const RecordType *Record
5435 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005437 diag::note_previous_decl)
5438 << S.Context.getTagDeclType(Record->getDecl());
5439 }
5440 break;
5441 }
5442
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005443 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5444 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005445 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005446 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005448 case OR_Deleted: {
5449 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5450 << true << DestType << ArgsRange;
5451 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005452 OverloadingResult Ovl
5453 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005454 if (Ovl == OR_Deleted) {
5455 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005456 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005457 } else {
5458 llvm_unreachable("Inconsistent overload resolution?");
5459 }
5460 break;
5461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005463 case OR_Success:
5464 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005465 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005466 }
David Blaikie60deeee2012-01-17 08:24:58 +00005467 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Douglas Gregor85dabae2009-12-16 01:38:02 +00005469 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005470 if (Entity.getKind() == InitializedEntity::EK_Member &&
5471 isa<CXXConstructorDecl>(S.CurContext)) {
5472 // This is implicit default-initialization of a const member in
5473 // a constructor. Complain that it needs to be explicitly
5474 // initialized.
5475 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5476 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5477 << Constructor->isImplicit()
5478 << S.Context.getTypeDeclType(Constructor->getParent())
5479 << /*const=*/1
5480 << Entity.getName();
5481 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5482 << Entity.getName();
5483 } else {
5484 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5485 << DestType << (bool)DestType->getAs<RecordType>();
5486 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005487 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005488
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005489 case FK_Incomplete:
5490 S.RequireCompleteType(Kind.getLocation(), DestType,
5491 diag::err_init_incomplete_type);
5492 break;
5493
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005494 case FK_ListInitializationFailed: {
5495 // Run the init list checker again to emit diagnostics.
5496 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5497 QualType DestType = Entity.getType();
5498 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005499 DestType, /*VerifyOnly=*/false,
5500 Kind.getKind() != InitializationKind::IK_Direct ||
5501 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005502 assert(DiagnoseInitList.HadError() &&
5503 "Inconsistent init list check result.");
5504 break;
5505 }
John McCall4124c492011-10-17 18:40:02 +00005506
5507 case FK_PlaceholderType: {
5508 // FIXME: Already diagnosed!
5509 break;
5510 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005511
5512 case FK_InitListElementCopyFailure: {
5513 // Try to perform all copies again.
5514 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5515 unsigned NumInits = InitList->getNumInits();
5516 QualType DestType = Entity.getType();
5517 QualType E;
5518 bool Success = S.isStdInitializerList(DestType, &E);
5519 (void)Success;
5520 assert(Success && "Where did the std::initializer_list go?");
5521 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5522 S.Context.getConstantArrayType(E,
5523 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5524 NumInits),
5525 ArrayType::Normal, 0));
5526 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5527 0, HiddenArray);
5528 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5529 // where the init list type is wrong, e.g.
5530 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5531 // FIXME: Emit a note if we hit the limit?
5532 int ErrorCount = 0;
5533 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5534 Element.setElementIndex(i);
5535 ExprResult Init = S.Owned(InitList->getInit(i));
5536 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5537 .isInvalid())
5538 ++ErrorCount;
5539 }
5540 break;
5541 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005543
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005544 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005545 return true;
5546}
Douglas Gregore1314a62009-12-18 05:02:21 +00005547
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005548void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005549 switch (SequenceKind) {
5550 case FailedSequence: {
5551 OS << "Failed sequence: ";
5552 switch (Failure) {
5553 case FK_TooManyInitsForReference:
5554 OS << "too many initializers for reference";
5555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005557 case FK_ArrayNeedsInitList:
5558 OS << "array requires initializer list";
5559 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005561 case FK_ArrayNeedsInitListOrStringLiteral:
5562 OS << "array requires initializer list or string literal";
5563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Douglas Gregore2f943b2011-02-22 18:29:51 +00005565 case FK_ArrayTypeMismatch:
5566 OS << "array type mismatch";
5567 break;
5568
5569 case FK_NonConstantArrayInit:
5570 OS << "non-constant array initializer";
5571 break;
5572
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005573 case FK_AddressOfOverloadFailed:
5574 OS << "address of overloaded function failed";
5575 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005577 case FK_ReferenceInitOverloadFailed:
5578 OS << "overload resolution for reference initialization failed";
5579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005581 case FK_NonConstLValueReferenceBindingToTemporary:
5582 OS << "non-const lvalue reference bound to temporary";
5583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005585 case FK_NonConstLValueReferenceBindingToUnrelated:
5586 OS << "non-const lvalue reference bound to unrelated type";
5587 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005589 case FK_RValueReferenceBindingToLValue:
5590 OS << "rvalue reference bound to an lvalue";
5591 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005593 case FK_ReferenceInitDropsQualifiers:
5594 OS << "reference initialization drops qualifiers";
5595 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005597 case FK_ReferenceInitFailed:
5598 OS << "reference initialization failed";
5599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005601 case FK_ConversionFailed:
5602 OS << "conversion failed";
5603 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
John Wiegley01296292011-04-08 18:41:53 +00005605 case FK_ConversionFromPropertyFailed:
5606 OS << "conversion from property failed";
5607 break;
5608
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005609 case FK_TooManyInitsForScalar:
5610 OS << "too many initializers for scalar";
5611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005613 case FK_ReferenceBindingToInitList:
5614 OS << "referencing binding to initializer list";
5615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005617 case FK_InitListBadDestinationType:
5618 OS << "initializer list for non-aggregate, non-scalar type";
5619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005621 case FK_UserConversionOverloadFailed:
5622 OS << "overloading failed for user-defined conversion";
5623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005624
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005625 case FK_ConstructorOverloadFailed:
5626 OS << "constructor overloading failed";
5627 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005629 case FK_DefaultInitOfConst:
5630 OS << "default initialization of a const variable";
5631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005633 case FK_Incomplete:
5634 OS << "initialization of incomplete type";
5635 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005636
5637 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005638 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005639 break;
5640
John McCalla59dc2f2012-01-05 00:13:19 +00005641 case FK_VariableLengthArrayHasInitializer:
5642 OS << "variable length array has an initializer";
5643 break;
5644
John McCall4124c492011-10-17 18:40:02 +00005645 case FK_PlaceholderType:
5646 OS << "initializer expression isn't contextually valid";
5647 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005648
5649 case FK_ListConstructorOverloadFailed:
5650 OS << "list constructor overloading failed";
5651 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005652
5653 case FK_InitListElementCopyFailure:
5654 OS << "copy construction of initializer list element failed";
5655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005657 OS << '\n';
5658 return;
5659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005661 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005662 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005663 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664
Sebastian Redld201edf2011-06-05 13:59:11 +00005665 case NormalSequence:
5666 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005667 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005670 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5671 if (S != step_begin()) {
5672 OS << " -> ";
5673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005675 switch (S->Kind) {
5676 case SK_ResolveAddressOfOverloadedFunction:
5677 OS << "resolve address of overloaded function";
5678 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005679
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005680 case SK_CastDerivedToBaseRValue:
5681 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5682 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005684 case SK_CastDerivedToBaseXValue:
5685 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005687
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005688 case SK_CastDerivedToBaseLValue:
5689 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5690 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005692 case SK_BindReference:
5693 OS << "bind reference to lvalue";
5694 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005696 case SK_BindReferenceToTemporary:
5697 OS << "bind reference to a temporary";
5698 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005700 case SK_ExtraneousCopyToTemporary:
5701 OS << "extraneous C++03 copy to temporary";
5702 break;
5703
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005704 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005705 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005706 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005707
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005708 case SK_QualificationConversionRValue:
5709 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005710 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005711
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005712 case SK_QualificationConversionXValue:
5713 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005714 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005715
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005716 case SK_QualificationConversionLValue:
5717 OS << "qualification conversion (lvalue)";
5718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005720 case SK_ConversionSequence:
5721 OS << "implicit conversion sequence (";
5722 S->ICS->DebugPrint(); // FIXME: use OS
5723 OS << ")";
5724 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005726 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005727 OS << "list aggregate initialization";
5728 break;
5729
5730 case SK_ListConstructorCall:
5731 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Sebastian Redl29526f02011-11-27 16:50:07 +00005734 case SK_UnwrapInitList:
5735 OS << "unwrap reference initializer list";
5736 break;
5737
5738 case SK_RewrapInitList:
5739 OS << "rewrap reference initializer list";
5740 break;
5741
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005742 case SK_ConstructorInitialization:
5743 OS << "constructor initialization";
5744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005746 case SK_ZeroInitialization:
5747 OS << "zero initialization";
5748 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005750 case SK_CAssignment:
5751 OS << "C assignment";
5752 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005754 case SK_StringInit:
5755 OS << "string initialization";
5756 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005757
5758 case SK_ObjCObjectConversion:
5759 OS << "Objective-C object conversion";
5760 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005761
5762 case SK_ArrayInit:
5763 OS << "array initialization";
5764 break;
John McCall31168b02011-06-15 23:02:42 +00005765
5766 case SK_PassByIndirectCopyRestore:
5767 OS << "pass by indirect copy and restore";
5768 break;
5769
5770 case SK_PassByIndirectRestore:
5771 OS << "pass by indirect restore";
5772 break;
5773
5774 case SK_ProduceObjCObject:
5775 OS << "Objective-C object retension";
5776 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005777
5778 case SK_StdInitializerList:
5779 OS << "std::initializer_list from initializer list";
5780 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005781 }
5782 }
5783}
5784
5785void InitializationSequence::dump() const {
5786 dump(llvm::errs());
5787}
5788
Richard Smith66e05fe2012-01-18 05:21:49 +00005789static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5790 QualType EntityType,
5791 const Expr *PreInit,
5792 const Expr *PostInit) {
5793 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5794 return;
5795
5796 // A narrowing conversion can only appear as the final implicit conversion in
5797 // an initialization sequence.
5798 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5799 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5800 return;
5801
5802 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5803 const StandardConversionSequence *SCS = 0;
5804 switch (ICS.getKind()) {
5805 case ImplicitConversionSequence::StandardConversion:
5806 SCS = &ICS.Standard;
5807 break;
5808 case ImplicitConversionSequence::UserDefinedConversion:
5809 SCS = &ICS.UserDefined.After;
5810 break;
5811 case ImplicitConversionSequence::AmbiguousConversion:
5812 case ImplicitConversionSequence::EllipsisConversion:
5813 case ImplicitConversionSequence::BadConversion:
5814 return;
5815 }
5816
5817 // Determine the type prior to the narrowing conversion. If a conversion
5818 // operator was used, this may be different from both the type of the entity
5819 // and of the pre-initialization expression.
5820 QualType PreNarrowingType = PreInit->getType();
5821 if (Seq.step_begin() + 1 != Seq.step_end())
5822 PreNarrowingType = Seq.step_end()[-2].Type;
5823
5824 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5825 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005826 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005827 case NK_Not_Narrowing:
5828 // No narrowing occurred.
5829 return;
5830
5831 case NK_Type_Narrowing:
5832 // This was a floating-to-integer conversion, which is always considered a
5833 // narrowing conversion even if the value is a constant and can be
5834 // represented exactly as an integer.
5835 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005836 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5837 diag::warn_init_list_type_narrowing
5838 : S.isSFINAEContext()?
5839 diag::err_init_list_type_narrowing_sfinae
5840 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005841 << PostInit->getSourceRange()
5842 << PreNarrowingType.getLocalUnqualifiedType()
5843 << EntityType.getLocalUnqualifiedType();
5844 break;
5845
5846 case NK_Constant_Narrowing:
5847 // A constant value was narrowed.
5848 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005849 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5850 diag::warn_init_list_constant_narrowing
5851 : S.isSFINAEContext()?
5852 diag::err_init_list_constant_narrowing_sfinae
5853 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005854 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005855 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005856 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005857 break;
5858
5859 case NK_Variable_Narrowing:
5860 // A variable's value may have been narrowed.
5861 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005862 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5863 diag::warn_init_list_variable_narrowing
5864 : S.isSFINAEContext()?
5865 diag::err_init_list_variable_narrowing_sfinae
5866 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005867 << PostInit->getSourceRange()
5868 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005869 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005870 break;
5871 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005872
5873 llvm::SmallString<128> StaticCast;
5874 llvm::raw_svector_ostream OS(StaticCast);
5875 OS << "static_cast<";
5876 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5877 // It's important to use the typedef's name if there is one so that the
5878 // fixit doesn't break code using types like int64_t.
5879 //
5880 // FIXME: This will break if the typedef requires qualification. But
5881 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005882 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005883 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5884 OS << BT->getName(S.getLangOptions());
5885 else {
5886 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5887 // with a broken cast.
5888 return;
5889 }
5890 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00005891 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5892 << PostInit->getSourceRange()
5893 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005894 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00005895 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005896}
5897
Douglas Gregore1314a62009-12-18 05:02:21 +00005898//===----------------------------------------------------------------------===//
5899// Initialization helper functions
5900//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005901bool
5902Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5903 ExprResult Init) {
5904 if (Init.isInvalid())
5905 return false;
5906
5907 Expr *InitE = Init.get();
5908 assert(InitE && "No initialization expression");
5909
5910 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5911 SourceLocation());
5912 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005913 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005914}
5915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005916ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005917Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5918 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005919 ExprResult Init,
5920 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005921 if (Init.isInvalid())
5922 return ExprError();
5923
John McCall1f425642010-11-11 03:21:53 +00005924 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005925 assert(InitE && "No initialization expression?");
5926
5927 if (EqualLoc.isInvalid())
5928 EqualLoc = InitE->getLocStart();
5929
5930 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5931 EqualLoc);
5932 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5933 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005934
Richard Smith66e05fe2012-01-18 05:21:49 +00005935 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5936
5937 if (!Result.isInvalid() && TopLevelOfInitList)
5938 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
5939 InitE, Result.get());
5940
5941 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00005942}