blob: 903c0c4b18c71810e6a73722354fccc968aeabea [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.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (S.getLangOpts().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())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000121 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000122 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())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000127 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000128 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;
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000176 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000177 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) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000292 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000293 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");
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000357 SourceLocation Loc = ILE->getLocStart();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 if (ILE->getSyntacticForm())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000359 Loc = ILE->getSyntacticForm()->getLocStart();
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
David Blaikie40ed2972012-06-06 20:45:41 +0000378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000379 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,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000549 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000550 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) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000607 QualType ExprTy = T;
608 if (!ExprTy->isArrayType())
609 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000610 IList->setType(ExprTy);
611 StructuredList->setType(ExprTy);
612 }
Eli Friedman85f54972008-05-25 13:22:35 +0000613 if (hadError)
614 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615
Eli Friedman85f54972008-05-25 13:22:35 +0000616 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000617 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000618 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000619 if (SemaRef.getLangOpts().CPlusPlus ||
620 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000621 IList->getType()->isVectorType())) {
622 hadError = true;
623 }
624 return;
625 }
626
Eli Friedmanbd327452009-05-29 20:20:05 +0000627 if (StructuredIndex == 1 &&
628 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000630 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000631 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000632 hadError = true;
633 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000634 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000635 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000636 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000637 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000638 // Don't complain for incomplete types, since we'll get an error
639 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000640 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000641 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000642 CurrentObjectType->isArrayType()? 0 :
643 CurrentObjectType->isVectorType()? 1 :
644 CurrentObjectType->isScalarType()? 2 :
645 CurrentObjectType->isUnionType()? 3 :
646 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000647
648 unsigned DK = diag::warn_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000649 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000650 DK = diag::err_excess_initializers;
651 hadError = true;
652 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000653 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000654 DK = diag::err_excess_initializers;
655 hadError = true;
656 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000657
Chris Lattnerb0912a52009-02-24 22:50:46 +0000658 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000659 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000660 }
661 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000662
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000663 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
664 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000666 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000667 << FixItHint::CreateRemoval(IList->getLocStart())
668 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000669}
670
Anders Carlsson6cabf312010-01-23 23:23:01 +0000671void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000672 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000673 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000674 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000675 unsigned &Index,
676 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000677 unsigned &StructuredIndex,
678 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000679 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
680 // Explicitly braced initializer for complex type can be real+imaginary
681 // parts.
682 CheckComplexType(Entity, IList, DeclType, Index,
683 StructuredList, StructuredIndex);
684 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000685 CheckScalarType(Entity, IList, DeclType, Index,
686 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000687 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000689 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000690 } else if (DeclType->isAggregateType()) {
691 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000692 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000693 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000694 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000695 StructuredList, StructuredIndex,
696 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000697 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000698 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000699 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000700 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000702 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000703 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000704 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000705 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000706 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
707 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000708 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000709 if (!VerifyOnly)
710 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
711 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000712 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000713 } else if (DeclType->isRecordType()) {
714 // C++ [dcl.init]p14:
715 // [...] If the class is an aggregate (8.5.1), and the initializer
716 // is a brace-enclosed list, see 8.5.1.
717 //
718 // Note: 8.5.1 is handled below; here, we diagnose the case where
719 // we have an initializer list and a destination type that is not
720 // an aggregate.
721 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000722 if (!VerifyOnly)
723 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
724 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000725 hadError = true;
726 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000727 CheckReferenceType(Entity, IList, DeclType, Index,
728 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000729 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000730 if (!VerifyOnly)
731 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
732 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000733 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000734 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000735 if (!VerifyOnly)
736 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
737 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000738 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000739 }
740}
741
Anders Carlsson6cabf312010-01-23 23:23:01 +0000742void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000743 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000744 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000745 unsigned &Index,
746 InitListExpr *StructuredList,
747 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000748 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000749 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
750 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000751 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000752 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000753 = getStructuredSubobjectInit(IList, Index, ElemType,
754 StructuredList, StructuredIndex,
755 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000756 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000757 newStructuredList, newStructuredIndex);
758 ++StructuredIndex;
759 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000760 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000761 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000762 return CheckScalarType(Entity, IList, ElemType, Index,
763 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000764 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000765 return CheckReferenceType(Entity, IList, ElemType, Index,
766 StructuredList, StructuredIndex);
767 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000768
John McCall5decec92011-02-21 07:57:55 +0000769 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
770 // arrayType can be incomplete if we're initializing a flexible
771 // array member. There's nothing we can do with the completed
772 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
John McCall5decec92011-02-21 07:57:55 +0000774 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000775 if (!VerifyOnly) {
776 CheckStringInit(Str, ElemType, arrayType, SemaRef);
777 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
778 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000779 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000780 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000781 }
John McCall5decec92011-02-21 07:57:55 +0000782
783 // Fall through for subaggregate initialization.
784
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000786 // C++ [dcl.init.aggr]p12:
787 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000788 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000789 // an initializer-list. If the initializer can initialize a
790 // member, the member is initialized. [...]
791
792 // FIXME: Better EqualLoc?
793 InitializationKind Kind =
794 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
795 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
796
797 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000798 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000799 ExprResult Result =
800 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
801 if (Result.isInvalid())
802 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000803
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000805 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000806 }
John McCall5decec92011-02-21 07:57:55 +0000807 ++Index;
808 return;
809 }
810
811 // Fall through for subaggregate initialization
812 } else {
813 // C99 6.7.8p13:
814 //
815 // The initializer for a structure or union object that has
816 // automatic storage duration shall be either an initializer
817 // list as described below, or a single expression that has
818 // compatible structure or union type. In the latter case, the
819 // initial value of the object, including unnamed members, is
820 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000821 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000822 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000823 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
824 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000825 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000826 if (ExprRes.isInvalid())
827 hadError = true;
828 else {
829 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
830 if (ExprRes.isInvalid())
831 hadError = true;
832 }
833 UpdateStructuredListElement(StructuredList, StructuredIndex,
834 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000835 ++Index;
836 return;
837 }
John Wiegley01296292011-04-08 18:41:53 +0000838 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000839 // Fall through for subaggregate initialization
840 }
841
842 // C++ [dcl.init.aggr]p12:
843 //
844 // [...] Otherwise, if the member is itself a non-empty
845 // subaggregate, brace elision is assumed and the initializer is
846 // considered for the initialization of the first member of
847 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000848 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +0000849 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000850 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
851 StructuredIndex);
852 ++StructuredIndex;
853 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000854 if (!VerifyOnly) {
855 // We cannot initialize this element, so let
856 // PerformCopyInitialization produce the appropriate diagnostic.
857 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
858 SemaRef.Owned(expr),
859 /*TopLevelOfInitList=*/true);
860 }
John McCall5decec92011-02-21 07:57:55 +0000861 hadError = true;
862 ++Index;
863 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000864 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000865}
866
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000867void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
868 InitListExpr *IList, QualType DeclType,
869 unsigned &Index,
870 InitListExpr *StructuredList,
871 unsigned &StructuredIndex) {
872 assert(Index == 0 && "Index in explicit init list must be zero");
873
874 // As an extension, clang supports complex initializers, which initialize
875 // a complex number component-wise. When an explicit initializer list for
876 // a complex number contains two two initializers, this extension kicks in:
877 // it exepcts the initializer list to contain two elements convertible to
878 // the element type of the complex type. The first element initializes
879 // the real part, and the second element intitializes the imaginary part.
880
881 if (IList->getNumInits() != 2)
882 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
883 StructuredIndex);
884
885 // This is an extension in C. (The builtin _Complex type does not exist
886 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000887 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000888 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
889 << IList->getSourceRange();
890
891 // Initialize the complex number.
892 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
893 InitializedEntity ElementEntity =
894 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
895
896 for (unsigned i = 0; i < 2; ++i) {
897 ElementEntity.setElementIndex(Index);
898 CheckSubElementType(ElementEntity, IList, elementType, Index,
899 StructuredList, StructuredIndex);
900 }
901}
902
903
Anders Carlsson6cabf312010-01-23 23:23:01 +0000904void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000905 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000906 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000909 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000910 if (!VerifyOnly)
911 SemaRef.Diag(IList->getLocStart(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000912 SemaRef.getLangOpts().CPlusPlus0x ?
Richard Smithc8239732011-10-18 21:39:00 +0000913 diag::warn_cxx98_compat_empty_scalar_initializer :
914 diag::err_empty_scalar_initializer)
915 << IList->getSourceRange();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000916 hadError = !SemaRef.getLangOpts().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000917 ++Index;
918 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000919 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000920 }
John McCall643169b2010-11-11 00:46:36 +0000921
922 Expr *expr = IList->getInit(Index);
923 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000924 if (!VerifyOnly)
925 SemaRef.Diag(SubIList->getLocStart(),
926 diag::warn_many_braces_around_scalar_init)
927 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000928
929 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
930 StructuredIndex);
931 return;
932 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000933 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000934 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000935 diag::err_designator_for_scalar_init)
936 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000937 hadError = true;
938 ++Index;
939 ++StructuredIndex;
940 return;
941 }
942
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000943 if (VerifyOnly) {
944 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
945 hadError = true;
946 ++Index;
947 return;
948 }
949
John McCall643169b2010-11-11 00:46:36 +0000950 ExprResult Result =
951 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000952 SemaRef.Owned(expr),
953 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000954
955 Expr *ResultExpr = 0;
956
957 if (Result.isInvalid())
958 hadError = true; // types weren't compatible.
959 else {
960 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
John McCall643169b2010-11-11 00:46:36 +0000962 if (ResultExpr != expr) {
963 // The type was promoted, update initializer list.
964 IList->setInit(Index, ResultExpr);
965 }
966 }
967 if (hadError)
968 ++StructuredIndex;
969 else
970 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
971 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000972}
973
Anders Carlsson6cabf312010-01-23 23:23:01 +0000974void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
975 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000976 unsigned &Index,
977 InitListExpr *StructuredList,
978 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000979 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000980 // FIXME: It would be wonderful if we could point at the actual member. In
981 // general, it would be useful to pass location information down the stack,
982 // so that we know the location (or decl) of the "current object" being
983 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000984 if (!VerifyOnly)
985 SemaRef.Diag(IList->getLocStart(),
986 diag::err_init_reference_member_uninitialized)
987 << DeclType
988 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000989 hadError = true;
990 ++Index;
991 ++StructuredIndex;
992 return;
993 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000994
995 Expr *expr = IList->getInit(Index);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000996 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000997 if (!VerifyOnly)
998 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
999 << DeclType << IList->getSourceRange();
1000 hadError = true;
1001 ++Index;
1002 ++StructuredIndex;
1003 return;
1004 }
1005
1006 if (VerifyOnly) {
1007 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1008 hadError = true;
1009 ++Index;
1010 return;
1011 }
1012
1013 ExprResult Result =
1014 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1015 SemaRef.Owned(expr),
1016 /*TopLevelOfInitList=*/true);
1017
1018 if (Result.isInvalid())
1019 hadError = true;
1020
1021 expr = Result.takeAs<Expr>();
1022 IList->setInit(Index, expr);
1023
1024 if (hadError)
1025 ++StructuredIndex;
1026 else
1027 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1028 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001029}
1030
Anders Carlsson6cabf312010-01-23 23:23:01 +00001031void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001032 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001033 unsigned &Index,
1034 InitListExpr *StructuredList,
1035 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001036 const VectorType *VT = DeclType->getAs<VectorType>();
1037 unsigned maxElements = VT->getNumElements();
1038 unsigned numEltsInit = 0;
1039 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001040
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001041 if (Index >= IList->getNumInits()) {
1042 // Make sure the element type can be value-initialized.
1043 if (VerifyOnly)
1044 CheckValueInitializable(
1045 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1046 return;
1047 }
1048
David Blaikiebbafb8a2012-03-11 07:00:24 +00001049 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001050 // If the initializing element is a vector, try to copy-initialize
1051 // instead of breaking it apart (which is doomed to failure anyway).
1052 Expr *Init = IList->getInit(Index);
1053 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001054 if (VerifyOnly) {
1055 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1056 hadError = true;
1057 ++Index;
1058 return;
1059 }
1060
John McCall6a16b2f2010-10-30 00:11:39 +00001061 ExprResult Result =
1062 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001063 SemaRef.Owned(Init),
1064 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001065
1066 Expr *ResultExpr = 0;
1067 if (Result.isInvalid())
1068 hadError = true; // types weren't compatible.
1069 else {
1070 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071
John McCall6a16b2f2010-10-30 00:11:39 +00001072 if (ResultExpr != Init) {
1073 // The type was promoted, update initializer list.
1074 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001075 }
1076 }
John McCall6a16b2f2010-10-30 00:11:39 +00001077 if (hadError)
1078 ++StructuredIndex;
1079 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001080 UpdateStructuredListElement(StructuredList, StructuredIndex,
1081 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001082 ++Index;
1083 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCall6a16b2f2010-10-30 00:11:39 +00001086 InitializedEntity ElementEntity =
1087 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088
John McCall6a16b2f2010-10-30 00:11:39 +00001089 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1090 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001091 if (Index >= IList->getNumInits()) {
1092 if (VerifyOnly)
1093 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001094 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
John McCall6a16b2f2010-10-30 00:11:39 +00001097 ElementEntity.setElementIndex(Index);
1098 CheckSubElementType(ElementEntity, IList, elementType, Index,
1099 StructuredList, StructuredIndex);
1100 }
1101 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001102 }
John McCall6a16b2f2010-10-30 00:11:39 +00001103
1104 InitializedEntity ElementEntity =
1105 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001106
John McCall6a16b2f2010-10-30 00:11:39 +00001107 // OpenCL initializers allows vectors to be constructed from vectors.
1108 for (unsigned i = 0; i < maxElements; ++i) {
1109 // Don't attempt to go past the end of the init list
1110 if (Index >= IList->getNumInits())
1111 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
John McCall6a16b2f2010-10-30 00:11:39 +00001113 ElementEntity.setElementIndex(Index);
1114
1115 QualType IType = IList->getInit(Index)->getType();
1116 if (!IType->isVectorType()) {
1117 CheckSubElementType(ElementEntity, IList, elementType, Index,
1118 StructuredList, StructuredIndex);
1119 ++numEltsInit;
1120 } else {
1121 QualType VecType;
1122 const VectorType *IVT = IType->getAs<VectorType>();
1123 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001124
John McCall6a16b2f2010-10-30 00:11:39 +00001125 if (IType->isExtVectorType())
1126 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1127 else
1128 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001129 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001130 CheckSubElementType(ElementEntity, IList, VecType, Index,
1131 StructuredList, StructuredIndex);
1132 numEltsInit += numIElts;
1133 }
1134 }
1135
1136 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001137 if (numEltsInit != maxElements) {
1138 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001139 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001140 diag::err_vector_incorrect_num_initializers)
1141 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1142 hadError = true;
1143 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001144}
1145
Anders Carlsson6cabf312010-01-23 23:23:01 +00001146void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001147 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001148 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001149 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001150 unsigned &Index,
1151 InitListExpr *StructuredList,
1152 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001153 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1154
Steve Narofff8ecff22008-05-01 22:18:59 +00001155 // Check for the special-case of initializing an array with a string.
1156 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001157 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001158 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001159 // We place the string literal directly into the resulting
1160 // initializer list. This is the only place where the structure
1161 // of the structured initializer list doesn't match exactly,
1162 // because doing so would involve allocating one character
1163 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001165 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001166 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1167 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1168 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001169 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001170 return;
1171 }
1172 }
John McCall66884dd2011-02-21 07:22:22 +00001173 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001174 // Check for VLAs; in standard C it would be possible to check this
1175 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1176 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001177 if (!VerifyOnly)
1178 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1179 diag::err_variable_object_no_init)
1180 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001181 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001182 ++Index;
1183 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001184 return;
1185 }
1186
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001187 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001188 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1189 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001191 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001192 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001193 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001194 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001195 maxElementsKnown = true;
1196 }
1197
John McCall66884dd2011-02-21 07:22:22 +00001198 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001199 while (Index < IList->getNumInits()) {
1200 Expr *Init = IList->getInit(Index);
1201 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001202 // If we're not the subobject that matches up with the '{' for
1203 // the designator, we shouldn't be handling the
1204 // designator. Return immediately.
1205 if (!SubobjectIsDesignatorContext)
1206 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001207
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001208 // Handle this designated initializer. elementIndex will be
1209 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001210 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001211 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001212 StructuredList, StructuredIndex, true,
1213 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001214 hadError = true;
1215 continue;
1216 }
1217
Douglas Gregor033d1252009-01-23 16:54:12 +00001218 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001219 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001220 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001221 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001222 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001223
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001224 // If the array is of incomplete type, keep track of the number of
1225 // elements in the initializer.
1226 if (!maxElementsKnown && elementIndex > maxElements)
1227 maxElements = elementIndex;
1228
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001229 continue;
1230 }
1231
1232 // If we know the maximum number of elements, and we've already
1233 // hit it, stop consuming elements in the initializer list.
1234 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001235 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001236
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001239 Entity);
1240 // Check this element.
1241 CheckSubElementType(ElementEntity, IList, elementType, Index,
1242 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001243 ++elementIndex;
1244
1245 // If the array is of incomplete type, keep track of the number of
1246 // elements in the initializer.
1247 if (!maxElementsKnown && elementIndex > maxElements)
1248 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001249 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001250 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001251 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001252 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001253 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001254 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001255 // Sizing an array implicitly to zero is not allowed by ISO C,
1256 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001257 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001259 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001260
Mike Stump11289f42009-09-09 15:08:12 +00001261 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001262 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001263 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001264 if (!hadError && VerifyOnly) {
1265 // Check if there are any members of the array that get value-initialized.
1266 // If so, check if doing that is possible.
1267 // FIXME: This needs to detect holes left by designated initializers too.
1268 if (maxElementsKnown && elementIndex < maxElements)
1269 CheckValueInitializable(InitializedEntity::InitializeElement(
1270 SemaRef.Context, 0, Entity));
1271 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001272}
1273
Eli Friedman3fa64df2011-08-23 22:24:57 +00001274bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1275 Expr *InitExpr,
1276 FieldDecl *Field,
1277 bool TopLevelObject) {
1278 // Handle GNU flexible array initializers.
1279 unsigned FlexArrayDiag;
1280 if (isa<InitListExpr>(InitExpr) &&
1281 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1282 // Empty flexible array init always allowed as an extension
1283 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001284 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001285 // Disallow flexible array init in C++; it is not required for gcc
1286 // compatibility, and it needs work to IRGen correctly in general.
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (!TopLevelObject) {
1289 // Disallow flexible array init on non-top-level object
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1292 // Disallow flexible array init on anything which is not a variable.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1295 // Disallow flexible array init on local variables.
1296 FlexArrayDiag = diag::err_flexible_array_init;
1297 } else {
1298 // Allow other cases.
1299 FlexArrayDiag = diag::ext_flexible_array_init;
1300 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001301
1302 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001303 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001304 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001305 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001306 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1307 << Field;
1308 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001309
1310 return FlexArrayDiag != diag::ext_flexible_array_init;
1311}
1312
Anders Carlsson6cabf312010-01-23 23:23:01 +00001313void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001314 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001315 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001316 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001317 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001318 unsigned &Index,
1319 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001320 unsigned &StructuredIndex,
1321 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001322 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001323
Eli Friedman23a9e312008-05-19 19:16:24 +00001324 // If the record is invalid, some of it's members are invalid. To avoid
1325 // confusion, we forgo checking the intializer for the entire record.
1326 if (structDecl->isInvalidDecl()) {
1327 hadError = true;
1328 return;
Mike Stump11289f42009-09-09 15:08:12 +00001329 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001330
1331 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001332 // Value-initialize the first named member of the union.
1333 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1334 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1335 Field != FieldEnd; ++Field) {
1336 if (Field->getDeclName()) {
1337 if (VerifyOnly)
1338 CheckValueInitializable(
David Blaikie40ed2972012-06-06 20:45:41 +00001339 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001340 else
David Blaikie40ed2972012-06-06 20:45:41 +00001341 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001342 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001343 }
1344 }
1345 return;
1346 }
1347
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001348 // If structDecl is a forward declaration, this loop won't do
1349 // anything except look at designated initializers; That's okay,
1350 // because an error should get printed out elsewhere. It might be
1351 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001352 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001353 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001354 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001355 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001356 while (Index < IList->getNumInits()) {
1357 Expr *Init = IList->getInit(Index);
1358
1359 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001360 // If we're not the subobject that matches up with the '{' for
1361 // the designator, we shouldn't be handling the
1362 // designator. Return immediately.
1363 if (!SubobjectIsDesignatorContext)
1364 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001365
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001366 // Handle this designated initializer. Field will be updated to
1367 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001368 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001369 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001370 StructuredList, StructuredIndex,
1371 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001372 hadError = true;
1373
Douglas Gregora9add4e2009-02-12 19:00:39 +00001374 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001375
1376 // Disable check for missing fields when designators are used.
1377 // This matches gcc behaviour.
1378 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001379 continue;
1380 }
1381
1382 if (Field == FieldEnd) {
1383 // We've run out of fields. We're done.
1384 break;
1385 }
1386
Douglas Gregora9add4e2009-02-12 19:00:39 +00001387 // We've already initialized a member of a union. We're done.
1388 if (InitializedSomething && DeclType->isUnionType())
1389 break;
1390
Douglas Gregor91f84212008-12-11 16:49:14 +00001391 // If we've hit the flexible array member at the end, we're done.
1392 if (Field->getType()->isIncompleteArrayType())
1393 break;
1394
Douglas Gregor51695702009-01-29 16:53:55 +00001395 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001396 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001397 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001398 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001399 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001400
Douglas Gregora82064c2011-06-29 21:51:31 +00001401 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001402 bool InvalidUse;
1403 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001404 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001405 else
David Blaikie40ed2972012-06-06 20:45:41 +00001406 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001407 IList->getInit(Index)->getLocStart());
1408 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001409 ++Index;
1410 ++Field;
1411 hadError = true;
1412 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001413 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001414
Anders Carlsson6cabf312010-01-23 23:23:01 +00001415 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001416 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001417 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1418 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001419 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001420
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001421 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001422 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001423 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001424 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001425
1426 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001427 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001428
John McCalle40b58e2010-03-11 19:32:38 +00001429 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001430 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1431 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1432 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001433 // It is possible we have one or more unnamed bitfields remaining.
1434 // Find first (if any) named field and emit warning.
1435 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1436 it != end; ++it) {
1437 if (!it->isUnnamedBitfield()) {
1438 SemaRef.Diag(IList->getSourceRange().getEnd(),
1439 diag::warn_missing_field_initializers) << it->getName();
1440 break;
1441 }
1442 }
1443 }
1444
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001445 // Check that any remaining fields can be value-initialized.
1446 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1447 !Field->getType()->isIncompleteArrayType()) {
1448 // FIXME: Should check for holes left by designated initializers too.
1449 for (; Field != FieldEnd && !hadError; ++Field) {
1450 if (!Field->isUnnamedBitfield())
1451 CheckValueInitializable(
David Blaikie40ed2972012-06-06 20:45:41 +00001452 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001453 }
1454 }
1455
Mike Stump11289f42009-09-09 15:08:12 +00001456 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001457 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001458 return;
1459
David Blaikie40ed2972012-06-06 20:45:41 +00001460 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001461 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001462 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001463 ++Index;
1464 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001465 }
1466
Anders Carlsson6cabf312010-01-23 23:23:01 +00001467 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001468 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469
Anders Carlsson6cabf312010-01-23 23:23:01 +00001470 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001472 StructuredList, StructuredIndex);
1473 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001475 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001476}
Steve Narofff8ecff22008-05-01 22:18:59 +00001477
Douglas Gregord5846a12009-04-15 06:41:24 +00001478/// \brief Expand a field designator that refers to a member of an
1479/// anonymous struct or union into a series of field designators that
1480/// refers to the field within the appropriate subobject.
1481///
Douglas Gregord5846a12009-04-15 06:41:24 +00001482static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001483 DesignatedInitExpr *DIE,
1484 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001485 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001486 typedef DesignatedInitExpr::Designator Designator;
1487
Douglas Gregord5846a12009-04-15 06:41:24 +00001488 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001489 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001490 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1491 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1492 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001493 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001494 DIE->getDesignator(DesigIdx)->getDotLoc(),
1495 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1496 else
1497 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1498 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001499 assert(isa<FieldDecl>(*PI));
1500 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001501 }
1502
1503 // Expand the current designator into the set of replacement
1504 // designators, so we have a full subobject path down to where the
1505 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001506 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001507 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001508}
Mike Stump11289f42009-09-09 15:08:12 +00001509
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001510/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001511/// corresponds to FieldName.
1512static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1513 IdentifierInfo *FieldName) {
1514 assert(AnonField->isAnonymousStructOrUnion());
1515 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001516 while (IndirectFieldDecl *IF =
1517 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001518 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1519 return IF;
1520 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001521 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001522 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001523}
1524
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001525static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1526 DesignatedInitExpr *DIE) {
1527 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1528 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1529 for (unsigned I = 0; I < NumIndexExprs; ++I)
1530 IndexExprs[I] = DIE->getSubExpr(I + 1);
1531 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1532 DIE->size(), IndexExprs.data(),
1533 NumIndexExprs, DIE->getEqualOrColonLoc(),
1534 DIE->usesGNUSyntax(), DIE->getInit());
1535}
1536
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001537namespace {
1538
1539// Callback to only accept typo corrections that are for field members of
1540// the given struct or union.
1541class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1542 public:
1543 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1544 : Record(RD) {}
1545
1546 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1547 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1548 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1549 }
1550
1551 private:
1552 RecordDecl *Record;
1553};
1554
1555}
1556
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001557/// @brief Check the well-formedness of a C99 designated initializer.
1558///
1559/// Determines whether the designated initializer @p DIE, which
1560/// resides at the given @p Index within the initializer list @p
1561/// IList, is well-formed for a current object of type @p DeclType
1562/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001563/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001564/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001565///
1566/// @param IList The initializer list in which this designated
1567/// initializer occurs.
1568///
Douglas Gregora5324162009-04-15 04:56:10 +00001569/// @param DIE The designated initializer expression.
1570///
1571/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001572///
1573/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1574/// into which the designation in @p DIE should refer.
1575///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001576/// @param NextField If non-NULL and the first designator in @p DIE is
1577/// a field, this will be set to the field declaration corresponding
1578/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001579///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001580/// @param NextElementIndex If non-NULL and the first designator in @p
1581/// DIE is an array designator or GNU array-range designator, this
1582/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001583///
1584/// @param Index Index into @p IList where the designated initializer
1585/// @p DIE occurs.
1586///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001587/// @param StructuredList The initializer list expression that
1588/// describes all of the subobject initializers in the order they'll
1589/// actually be initialized.
1590///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001591/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001592bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001593InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001594 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001595 DesignatedInitExpr *DIE,
1596 unsigned DesigIdx,
1597 QualType &CurrentObjectType,
1598 RecordDecl::field_iterator *NextField,
1599 llvm::APSInt *NextElementIndex,
1600 unsigned &Index,
1601 InitListExpr *StructuredList,
1602 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001603 bool FinishSubobjectInit,
1604 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001605 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 // Check the actual initialization for the designated object type.
1607 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001608
1609 // Temporarily remove the designator expression from the
1610 // initializer list that the child calls see, so that we don't try
1611 // to re-process the designator.
1612 unsigned OldIndex = Index;
1613 IList->setInit(OldIndex, DIE->getInit());
1614
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001615 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001616 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001617
1618 // Restore the designated initializer expression in the syntactic
1619 // form of the initializer list.
1620 if (IList->getInit(OldIndex) != DIE->getInit())
1621 DIE->setInit(IList->getInit(OldIndex));
1622 IList->setInit(OldIndex, DIE);
1623
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001624 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001625 }
1626
Douglas Gregora5324162009-04-15 04:56:10 +00001627 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001628 bool IsFirstDesignator = (DesigIdx == 0);
1629 if (!VerifyOnly) {
1630 assert((IsFirstDesignator || StructuredList) &&
1631 "Need a non-designated initializer list to start from");
1632
1633 // Determine the structural initializer list that corresponds to the
1634 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001635 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001636 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1637 StructuredList, StructuredIndex,
1638 SourceRange(D->getStartLocation(),
1639 DIE->getSourceRange().getEnd()));
1640 assert(StructuredList && "Expected a structured initializer list");
1641 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001642
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001643 if (D->isFieldDesignator()) {
1644 // C99 6.7.8p7:
1645 //
1646 // If a designator has the form
1647 //
1648 // . identifier
1649 //
1650 // then the current object (defined below) shall have
1651 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001652 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001653 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654 if (!RT) {
1655 SourceLocation Loc = D->getDotLoc();
1656 if (Loc.isInvalid())
1657 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001658 if (!VerifyOnly)
1659 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001661 ++Index;
1662 return true;
1663 }
1664
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001665 // Note: we perform a linear search of the fields here, despite
1666 // the fact that we have a faster lookup method, because we always
1667 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001668 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001669 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001670 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001671 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001672 Field = RT->getDecl()->field_begin(),
1673 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 for (; Field != FieldEnd; ++Field) {
1675 if (Field->isUnnamedBitfield())
1676 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001678 // If we find a field representing an anonymous field, look in the
1679 // IndirectFieldDecl that follow for the designated initializer.
1680 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1681 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001682 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001683 // In verify mode, don't modify the original.
1684 if (VerifyOnly)
1685 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001686 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1687 D = DIE->getDesignator(DesigIdx);
1688 break;
1689 }
1690 }
David Blaikie40ed2972012-06-06 20:45:41 +00001691 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001692 break;
1693 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694 break;
1695
1696 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001697 }
1698
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001699 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001700 if (VerifyOnly) {
1701 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001702 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001703 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001704
Douglas Gregord5846a12009-04-15 06:41:24 +00001705 // There was no normal field in the struct with the designated
1706 // name. Perform another lookup for this name, which may find
1707 // something that we can't designate (e.g., a member function),
1708 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001709 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001710 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001711 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001712 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001713 // Name lookup didn't find anything. Determine whether this
1714 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001715 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001716 TypoCorrection Corrected = SemaRef.CorrectTypo(
1717 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001718 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001719 RT->getDecl());
1720 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001721 std::string CorrectedStr(
David Blaikiebbafb8a2012-03-11 07:00:24 +00001722 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001723 std::string CorrectedQuotedStr(
David Blaikiebbafb8a2012-03-11 07:00:24 +00001724 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001725 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001727 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001728 << FieldName << CurrentObjectType << CorrectedQuotedStr
1729 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001731 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001732 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001733 } else {
1734 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1735 << FieldName << CurrentObjectType;
1736 ++Index;
1737 return true;
1738 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001740
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001741 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001742 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001743 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001744 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001745 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001746 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001747 ++Index;
1748 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001749 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001750
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001751 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001752 // The replacement field comes from typo correction; find it
1753 // in the list of fields.
1754 FieldIndex = 0;
1755 Field = RT->getDecl()->field_begin();
1756 for (; Field != FieldEnd; ++Field) {
1757 if (Field->isUnnamedBitfield())
1758 continue;
1759
David Blaikie40ed2972012-06-06 20:45:41 +00001760 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001761 Field->getIdentifier() == ReplacementField->getIdentifier())
1762 break;
1763
1764 ++FieldIndex;
1765 }
1766 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001767 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001768
1769 // All of the fields of a union are located at the same place in
1770 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001771 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001772 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001773 if (!VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001774 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001775 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001776
Douglas Gregora82064c2011-06-29 21:51:31 +00001777 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001778 bool InvalidUse;
1779 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001780 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001781 else
David Blaikie40ed2972012-06-06 20:45:41 +00001782 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001784 ++Index;
1785 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001786 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001787
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001788 if (!VerifyOnly) {
1789 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00001790 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001791
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001792 // Make sure that our non-designated initializer list has space
1793 // for a subobject corresponding to this field.
1794 if (FieldIndex >= StructuredList->getNumInits())
1795 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1796 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001797
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001798 // This designator names a flexible array member.
1799 if (Field->getType()->isIncompleteArrayType()) {
1800 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001801 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001802 // We can't designate an object within the flexible array
1803 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001804 if (!VerifyOnly) {
1805 DesignatedInitExpr::Designator *NextD
1806 = DIE->getDesignator(DesigIdx + 1);
1807 SemaRef.Diag(NextD->getStartLocation(),
1808 diag::err_designator_into_flexible_array_member)
1809 << SourceRange(NextD->getStartLocation(),
1810 DIE->getSourceRange().getEnd());
1811 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001812 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001813 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001814 Invalid = true;
1815 }
1816
Chris Lattner001b29c2010-10-10 17:49:49 +00001817 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1818 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001819 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001820 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001821 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001822 diag::err_flexible_array_init_needs_braces)
1823 << DIE->getInit()->getSourceRange();
1824 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001825 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001826 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001827 Invalid = true;
1828 }
1829
Eli Friedman3fa64df2011-08-23 22:24:57 +00001830 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00001831 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001832 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001833 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001834
1835 if (Invalid) {
1836 ++Index;
1837 return true;
1838 }
1839
1840 // Initialize the array.
1841 bool prevHadError = hadError;
1842 unsigned newStructuredIndex = FieldIndex;
1843 unsigned OldIndex = Index;
1844 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001845
1846 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001847 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001848 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001849 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001850
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001851 IList->setInit(OldIndex, DIE);
1852 if (hadError && !prevHadError) {
1853 ++Field;
1854 ++FieldIndex;
1855 if (NextField)
1856 *NextField = Field;
1857 StructuredIndex = FieldIndex;
1858 return true;
1859 }
1860 } else {
1861 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00001862 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001863 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001865 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001866 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1868 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001869 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001870 true, false))
1871 return true;
1872 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873
1874 // Find the position of the next field to be initialized in this
1875 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001876 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001877 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001878
1879 // If this the first designator, our caller will continue checking
1880 // the rest of this struct/class/union subobject.
1881 if (IsFirstDesignator) {
1882 if (NextField)
1883 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001884 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001885 return false;
1886 }
1887
Douglas Gregor17bd0942009-01-28 23:36:17 +00001888 if (!FinishSubobjectInit)
1889 return false;
1890
Douglas Gregord5846a12009-04-15 06:41:24 +00001891 // We've already initialized something in the union; we're done.
1892 if (RT->getDecl()->isUnion())
1893 return hadError;
1894
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001895 // Check the remaining fields within this class/struct/union subobject.
1896 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
Anders Carlsson6cabf312010-01-23 23:23:01 +00001898 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001899 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001900 return hadError && !prevHadError;
1901 }
1902
1903 // C99 6.7.8p6:
1904 //
1905 // If a designator has the form
1906 //
1907 // [ constant-expression ]
1908 //
1909 // then the current object (defined below) shall have array
1910 // type and the expression shall be an integer constant
1911 // expression. If the array is of unknown size, any
1912 // nonnegative value is valid.
1913 //
1914 // Additionally, cope with the GNU extension that permits
1915 // designators of the form
1916 //
1917 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001918 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001919 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001920 if (!VerifyOnly)
1921 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1922 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001923 ++Index;
1924 return true;
1925 }
1926
1927 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001928 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1929 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001930 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001931 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932 DesignatedEndIndex = DesignatedStartIndex;
1933 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001934 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001935
Mike Stump11289f42009-09-09 15:08:12 +00001936 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001937 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001938 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001939 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001940 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001941
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001942 // Codegen can't handle evaluating array range designators that have side
1943 // effects, because we replicate the AST value for each initialized element.
1944 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1945 // elements with something that has a side effect, so codegen can emit an
1946 // "error unsupported" error instead of miscompiling the app.
1947 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001948 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001949 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001950 }
1951
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001952 if (isa<ConstantArrayType>(AT)) {
1953 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001954 DesignatedStartIndex
1955 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001956 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001957 DesignatedEndIndex
1958 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001959 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1960 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001961 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001962 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001963 diag::err_array_designator_too_large)
1964 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1965 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001966 ++Index;
1967 return true;
1968 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001969 } else {
1970 // Make sure the bit-widths and signedness match.
1971 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001972 DesignatedEndIndex
1973 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001974 else if (DesignatedStartIndex.getBitWidth() <
1975 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001976 DesignatedStartIndex
1977 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001978 DesignatedStartIndex.setIsUnsigned(true);
1979 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001980 }
Mike Stump11289f42009-09-09 15:08:12 +00001981
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001982 // Make sure that our non-designated initializer list has space
1983 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001984 if (!VerifyOnly &&
1985 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001986 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001987 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001988
Douglas Gregor17bd0942009-01-28 23:36:17 +00001989 // Repeatedly perform subobject initializations in the range
1990 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001991
Douglas Gregor17bd0942009-01-28 23:36:17 +00001992 // Move to the next designator
1993 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1994 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001996 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001997 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001998
Douglas Gregor17bd0942009-01-28 23:36:17 +00001999 while (DesignatedStartIndex <= DesignatedEndIndex) {
2000 // Recurse to check later designated subobjects.
2001 QualType ElementType = AT->getElementType();
2002 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002004 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2006 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002007 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002008 (DesignatedStartIndex == DesignatedEndIndex),
2009 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002010 return true;
2011
2012 // Move to the next index in the array that we'll be initializing.
2013 ++DesignatedStartIndex;
2014 ElementIndex = DesignatedStartIndex.getZExtValue();
2015 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002016
2017 // If this the first designator, our caller will continue checking
2018 // the rest of this array subobject.
2019 if (IsFirstDesignator) {
2020 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002021 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002022 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002023 return false;
2024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Douglas Gregor17bd0942009-01-28 23:36:17 +00002026 if (!FinishSubobjectInit)
2027 return false;
2028
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002029 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002030 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002032 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002033 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002034 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002035}
2036
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002037// Get the structured initializer list for a subobject of type
2038// @p CurrentObjectType.
2039InitListExpr *
2040InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2041 QualType CurrentObjectType,
2042 InitListExpr *StructuredList,
2043 unsigned StructuredIndex,
2044 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002045 if (VerifyOnly)
2046 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002047 Expr *ExistingInit = 0;
2048 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002049 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050 else if (StructuredIndex < StructuredList->getNumInits())
2051 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002053 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2054 return Result;
2055
2056 if (ExistingInit) {
2057 // We are creating an initializer list that initializes the
2058 // subobjects of the current object, but there was already an
2059 // initialization that completely initialized the current
2060 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002061 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002062 // struct X { int a, b; };
2063 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002064 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002065 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2066 // designated initializer re-initializes the whole
2067 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002068 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002069 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002070 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002071 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002072 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002073 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002074 << ExistingInit->getSourceRange();
2075 }
2076
Mike Stump11289f42009-09-09 15:08:12 +00002077 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002078 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2079 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002080 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002081
Eli Friedman91f5ae52012-02-23 02:25:10 +00002082 QualType ResultType = CurrentObjectType;
2083 if (!ResultType->isArrayType())
2084 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2085 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002086
Douglas Gregor6d00c992009-03-20 23:58:33 +00002087 // Pre-allocate storage for the structured initializer list.
2088 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002089 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002090 bool GotNumInits = false;
2091 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002092 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002093 GotNumInits = true;
2094 } else if (Index < IList->getNumInits()) {
2095 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002096 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002097 GotNumInits = true;
2098 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002099 }
2100
Mike Stump11289f42009-09-09 15:08:12 +00002101 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002102 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2103 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2104 NumElements = CAType->getSize().getZExtValue();
2105 // Simple heuristic so that we don't allocate a very large
2106 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002107 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002108 NumElements = 0;
2109 }
John McCall9dd450b2009-09-21 23:43:11 +00002110 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002111 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002112 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002113 RecordDecl *RDecl = RType->getDecl();
2114 if (RDecl->isUnion())
2115 NumElements = 1;
2116 else
Mike Stump11289f42009-09-09 15:08:12 +00002117 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002118 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002119 }
2120
Ted Kremenekac034612010-04-13 23:39:13 +00002121 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002122
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002123 // Link this new initializer list into the structured initializer
2124 // lists.
2125 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002126 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002127 else {
2128 Result->setSyntacticForm(IList);
2129 SyntacticToSemantic[IList] = Result;
2130 }
2131
2132 return Result;
2133}
2134
2135/// Update the initializer at index @p StructuredIndex within the
2136/// structured initializer list to the value @p expr.
2137void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2138 unsigned &StructuredIndex,
2139 Expr *expr) {
2140 // No structured initializer list to update
2141 if (!StructuredList)
2142 return;
2143
Ted Kremenekac034612010-04-13 23:39:13 +00002144 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2145 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002146 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002147 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002148 diag::warn_initializer_overrides)
2149 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002150 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002151 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002152 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002153 << PrevInit->getSourceRange();
2154 }
Mike Stump11289f42009-09-09 15:08:12 +00002155
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002156 ++StructuredIndex;
2157}
2158
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002159/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002160/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002161/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002162/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002163/// failure. Returns the index expression, possibly with an implicit cast
2164/// added, on success. If everything went okay, Value will receive the
2165/// value of the constant expression.
2166static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002167CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002168 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002169
2170 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002171 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2172 if (Result.isInvalid())
2173 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002174
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002175 if (Value.isSigned() && Value.isNegative())
2176 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002177 << Value.toString(10) << Index->getSourceRange();
2178
Douglas Gregor51650d32009-01-23 21:04:18 +00002179 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002180 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002181}
2182
John McCalldadc5752010-08-24 06:29:42 +00002183ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002184 SourceLocation Loc,
2185 bool GNUSyntax,
2186 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002187 typedef DesignatedInitExpr::Designator ASTDesignator;
2188
2189 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002190 SmallVector<ASTDesignator, 32> Designators;
2191 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002192
2193 // Build designators and check array designator expressions.
2194 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2195 const Designator &D = Desig.getDesignator(Idx);
2196 switch (D.getKind()) {
2197 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002198 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002199 D.getFieldLoc()));
2200 break;
2201
2202 case Designator::ArrayDesignator: {
2203 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2204 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002205 if (!Index->isTypeDependent() && !Index->isValueDependent())
2206 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2207 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002208 Invalid = true;
2209 else {
2210 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002211 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002212 D.getRBracketLoc()));
2213 InitExpressions.push_back(Index);
2214 }
2215 break;
2216 }
2217
2218 case Designator::ArrayRangeDesignator: {
2219 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2220 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2221 llvm::APSInt StartValue;
2222 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002223 bool StartDependent = StartIndex->isTypeDependent() ||
2224 StartIndex->isValueDependent();
2225 bool EndDependent = EndIndex->isTypeDependent() ||
2226 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002227 if (!StartDependent)
2228 StartIndex =
2229 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2230 if (!EndDependent)
2231 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2232
2233 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002234 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 else {
2236 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002237 if (StartDependent || EndDependent) {
2238 // Nothing to compute.
2239 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002240 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002241 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002242 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002243
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002244 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002245 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002246 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002247 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2248 Invalid = true;
2249 } else {
2250 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002251 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002252 D.getEllipsisLoc(),
2253 D.getRBracketLoc()));
2254 InitExpressions.push_back(StartIndex);
2255 InitExpressions.push_back(EndIndex);
2256 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002257 }
2258 break;
2259 }
2260 }
2261 }
2262
2263 if (Invalid || Init.isInvalid())
2264 return ExprError();
2265
2266 // Clear out the expressions within the designation.
2267 Desig.ClearExprs(*this);
2268
2269 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002270 = DesignatedInitExpr::Create(Context,
2271 Designators.data(), Designators.size(),
2272 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002273 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274
David Blaikiebbafb8a2012-03-11 07:00:24 +00002275 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002276 Diag(DIE->getLocStart(), diag::ext_designated_init)
2277 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002278
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002279 return Owned(DIE);
2280}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002282//===----------------------------------------------------------------------===//
2283// Initialization entity
2284//===----------------------------------------------------------------------===//
2285
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002286InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002287 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002289{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002290 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2291 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002292 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002293 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002294 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002295 Type = VT->getElementType();
2296 } else {
2297 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2298 assert(CT && "Unexpected type");
2299 Kind = EK_ComplexElement;
2300 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002301 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002302}
2303
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002305 CXXBaseSpecifier *Base,
2306 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002307{
2308 InitializedEntity Result;
2309 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002310 Result.Base = reinterpret_cast<uintptr_t>(Base);
2311 if (IsInheritedVirtualBase)
2312 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002313
Douglas Gregor1b303932009-12-22 15:35:07 +00002314 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002315 return Result;
2316}
2317
Douglas Gregor85dabae2009-12-16 01:38:02 +00002318DeclarationName InitializedEntity::getName() const {
2319 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002320 case EK_Parameter: {
2321 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2322 return (D ? D->getDeclName() : DeclarationName());
2323 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002324
2325 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002326 case EK_Member:
2327 return VariableOrMember->getDeclName();
2328
Douglas Gregor19666fb2012-02-15 16:57:26 +00002329 case EK_LambdaCapture:
2330 return Capture.Var->getDeclName();
2331
Douglas Gregor85dabae2009-12-16 01:38:02 +00002332 case EK_Result:
2333 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002334 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002335 case EK_Temporary:
2336 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002337 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002338 case EK_ArrayElement:
2339 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002340 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002341 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002342 return DeclarationName();
2343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344
David Blaikie8a40f702012-01-17 06:56:22 +00002345 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002346}
2347
Douglas Gregora4b592a2009-12-19 03:01:41 +00002348DeclaratorDecl *InitializedEntity::getDecl() const {
2349 switch (getKind()) {
2350 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002351 case EK_Member:
2352 return VariableOrMember;
2353
John McCall31168b02011-06-15 23:02:42 +00002354 case EK_Parameter:
2355 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2356
Douglas Gregora4b592a2009-12-19 03:01:41 +00002357 case EK_Result:
2358 case EK_Exception:
2359 case EK_New:
2360 case EK_Temporary:
2361 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002362 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002363 case EK_ArrayElement:
2364 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002365 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002366 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002367 case EK_LambdaCapture:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002368 return 0;
2369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002370
David Blaikie8a40f702012-01-17 06:56:22 +00002371 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002372}
2373
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002374bool InitializedEntity::allowsNRVO() const {
2375 switch (getKind()) {
2376 case EK_Result:
2377 case EK_Exception:
2378 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002379
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002380 case EK_Variable:
2381 case EK_Parameter:
2382 case EK_Member:
2383 case EK_New:
2384 case EK_Temporary:
2385 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002386 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002387 case EK_ArrayElement:
2388 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002389 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002390 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002391 case EK_LambdaCapture:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002392 break;
2393 }
2394
2395 return false;
2396}
2397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398//===----------------------------------------------------------------------===//
2399// Initialization sequence
2400//===----------------------------------------------------------------------===//
2401
2402void InitializationSequence::Step::Destroy() {
2403 switch (Kind) {
2404 case SK_ResolveAddressOfOverloadedFunction:
2405 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002406 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002407 case SK_CastDerivedToBaseLValue:
2408 case SK_BindReference:
2409 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002410 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002411 case SK_UserConversion:
2412 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002413 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002414 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002415 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002416 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002417 case SK_UnwrapInitList:
2418 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002419 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002420 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002421 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002422 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002423 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002424 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002425 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002426 case SK_PassByIndirectCopyRestore:
2427 case SK_PassByIndirectRestore:
2428 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002429 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002430 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432 case SK_ConversionSequence:
2433 delete ICS;
2434 }
2435}
2436
Douglas Gregor838fcc32010-03-26 20:14:36 +00002437bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002438 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002439}
2440
2441bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002442 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002443 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444
Douglas Gregor838fcc32010-03-26 20:14:36 +00002445 switch (getFailureKind()) {
2446 case FK_TooManyInitsForReference:
2447 case FK_ArrayNeedsInitList:
2448 case FK_ArrayNeedsInitListOrStringLiteral:
2449 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2450 case FK_NonConstLValueReferenceBindingToTemporary:
2451 case FK_NonConstLValueReferenceBindingToUnrelated:
2452 case FK_RValueReferenceBindingToLValue:
2453 case FK_ReferenceInitDropsQualifiers:
2454 case FK_ReferenceInitFailed:
2455 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002456 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002457 case FK_TooManyInitsForScalar:
2458 case FK_ReferenceBindingToInitList:
2459 case FK_InitListBadDestinationType:
2460 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002461 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002462 case FK_ArrayTypeMismatch:
2463 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002464 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002465 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002466 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002467 case FK_InitListElementCopyFailure:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002468 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002469 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470
Douglas Gregor838fcc32010-03-26 20:14:36 +00002471 case FK_ReferenceInitOverloadFailed:
2472 case FK_UserConversionOverloadFailed:
2473 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002474 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002475 return FailedOverloadResult == OR_Ambiguous;
2476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002477
David Blaikie8a40f702012-01-17 06:56:22 +00002478 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002479}
2480
Douglas Gregorb33eed02010-04-16 22:09:46 +00002481bool InitializationSequence::isConstructorInitialization() const {
2482 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2483}
2484
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002485void
2486InitializationSequence
2487::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2488 DeclAccessPair Found,
2489 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002490 Step S;
2491 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2492 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002493 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002494 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002495 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002496 Steps.push_back(S);
2497}
2498
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002500 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002501 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002502 switch (VK) {
2503 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2504 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2505 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002506 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507 S.Type = BaseType;
2508 Steps.push_back(S);
2509}
2510
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002511void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002512 bool BindingTemporary) {
2513 Step S;
2514 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2515 S.Type = T;
2516 Steps.push_back(S);
2517}
2518
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002519void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2520 Step S;
2521 S.Kind = SK_ExtraneousCopyToTemporary;
2522 S.Type = T;
2523 Steps.push_back(S);
2524}
2525
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002526void
2527InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2528 DeclAccessPair FoundDecl,
2529 QualType T,
2530 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 Step S;
2532 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002533 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002534 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002535 S.Function.Function = Function;
2536 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002537 Steps.push_back(S);
2538}
2539
2540void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002541 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002542 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002543 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002544 switch (VK) {
2545 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002546 S.Kind = SK_QualificationConversionRValue;
2547 break;
John McCall2536c6d2010-08-25 10:28:54 +00002548 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002549 S.Kind = SK_QualificationConversionXValue;
2550 break;
John McCall2536c6d2010-08-25 10:28:54 +00002551 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002552 S.Kind = SK_QualificationConversionLValue;
2553 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002554 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 S.Type = Ty;
2556 Steps.push_back(S);
2557}
2558
2559void InitializationSequence::AddConversionSequenceStep(
2560 const ImplicitConversionSequence &ICS,
2561 QualType T) {
2562 Step S;
2563 S.Kind = SK_ConversionSequence;
2564 S.Type = T;
2565 S.ICS = new ImplicitConversionSequence(ICS);
2566 Steps.push_back(S);
2567}
2568
Douglas Gregor51e77d52009-12-10 17:56:55 +00002569void InitializationSequence::AddListInitializationStep(QualType T) {
2570 Step S;
2571 S.Kind = SK_ListInitialization;
2572 S.Type = T;
2573 Steps.push_back(S);
2574}
2575
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002577InitializationSequence
2578::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2579 AccessSpecifier Access,
2580 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002581 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002582 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002583 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002584 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2585 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002586 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002587 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002588 S.Function.Function = Constructor;
2589 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002590 Steps.push_back(S);
2591}
2592
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002593void InitializationSequence::AddZeroInitializationStep(QualType T) {
2594 Step S;
2595 S.Kind = SK_ZeroInitialization;
2596 S.Type = T;
2597 Steps.push_back(S);
2598}
2599
Douglas Gregore1314a62009-12-18 05:02:21 +00002600void InitializationSequence::AddCAssignmentStep(QualType T) {
2601 Step S;
2602 S.Kind = SK_CAssignment;
2603 S.Type = T;
2604 Steps.push_back(S);
2605}
2606
Eli Friedman78275202009-12-19 08:11:05 +00002607void InitializationSequence::AddStringInitStep(QualType T) {
2608 Step S;
2609 S.Kind = SK_StringInit;
2610 S.Type = T;
2611 Steps.push_back(S);
2612}
2613
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002614void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2615 Step S;
2616 S.Kind = SK_ObjCObjectConversion;
2617 S.Type = T;
2618 Steps.push_back(S);
2619}
2620
Douglas Gregore2f943b2011-02-22 18:29:51 +00002621void InitializationSequence::AddArrayInitStep(QualType T) {
2622 Step S;
2623 S.Kind = SK_ArrayInit;
2624 S.Type = T;
2625 Steps.push_back(S);
2626}
2627
Richard Smithebeed412012-02-15 22:38:09 +00002628void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2629 Step S;
2630 S.Kind = SK_ParenthesizedArrayInit;
2631 S.Type = T;
2632 Steps.push_back(S);
2633}
2634
John McCall31168b02011-06-15 23:02:42 +00002635void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2636 bool shouldCopy) {
2637 Step s;
2638 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2639 : SK_PassByIndirectRestore);
2640 s.Type = type;
2641 Steps.push_back(s);
2642}
2643
2644void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2645 Step S;
2646 S.Kind = SK_ProduceObjCObject;
2647 S.Type = T;
2648 Steps.push_back(S);
2649}
2650
Sebastian Redlc1839b12012-01-17 22:49:42 +00002651void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2652 Step S;
2653 S.Kind = SK_StdInitializerList;
2654 S.Type = T;
2655 Steps.push_back(S);
2656}
2657
Sebastian Redl29526f02011-11-27 16:50:07 +00002658void InitializationSequence::RewrapReferenceInitList(QualType T,
2659 InitListExpr *Syntactic) {
2660 assert(Syntactic->getNumInits() == 1 &&
2661 "Can only rewrap trivial init lists.");
2662 Step S;
2663 S.Kind = SK_UnwrapInitList;
2664 S.Type = Syntactic->getInit(0)->getType();
2665 Steps.insert(Steps.begin(), S);
2666
2667 S.Kind = SK_RewrapInitList;
2668 S.Type = T;
2669 S.WrappingSyntacticList = Syntactic;
2670 Steps.push_back(S);
2671}
2672
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002674 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002675 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002676 this->Failure = Failure;
2677 this->FailedOverloadResult = Result;
2678}
2679
2680//===----------------------------------------------------------------------===//
2681// Attempt initialization
2682//===----------------------------------------------------------------------===//
2683
John McCall31168b02011-06-15 23:02:42 +00002684static void MaybeProduceObjCObject(Sema &S,
2685 InitializationSequence &Sequence,
2686 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002687 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00002688
2689 /// When initializing a parameter, produce the value if it's marked
2690 /// __attribute__((ns_consumed)).
2691 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2692 if (!Entity.isParameterConsumed())
2693 return;
2694
2695 assert(Entity.getType()->isObjCRetainableType() &&
2696 "consuming an object of unretainable type?");
2697 Sequence.AddProduceObjCObjectStep(Entity.getType());
2698
2699 /// When initializing a return value, if the return type is a
2700 /// retainable type, then returns need to immediately retain the
2701 /// object. If an autorelease is required, it will be done at the
2702 /// last instant.
2703 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2704 if (!Entity.getType()->isObjCRetainableType())
2705 return;
2706
2707 Sequence.AddProduceObjCObjectStep(Entity.getType());
2708 }
2709}
2710
Richard Smithd86812d2012-07-05 08:39:21 +00002711/// \brief When initializing from init list via constructor, handle
2712/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00002713///
Richard Smithd86812d2012-07-05 08:39:21 +00002714/// \return true if we have handled initialization of an object of type
2715/// std::initializer_list<T>, false otherwise.
2716static bool TryInitializerListConstruction(Sema &S,
2717 InitListExpr *List,
2718 QualType DestType,
2719 InitializationSequence &Sequence) {
2720 QualType E;
2721 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00002722 return false;
2723
Richard Smithd86812d2012-07-05 08:39:21 +00002724 // Check that each individual element can be copy-constructed. But since we
2725 // have no place to store further information, we'll recalculate everything
2726 // later.
2727 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2728 S.Context.getConstantArrayType(E,
2729 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2730 List->getNumInits()),
2731 ArrayType::Normal, 0));
2732 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2733 0, HiddenArray);
2734 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2735 Element.setElementIndex(i);
2736 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2737 Sequence.SetFailed(
2738 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redled2e5322011-12-22 14:44:04 +00002739 return true;
2740 }
2741 }
Richard Smithd86812d2012-07-05 08:39:21 +00002742 Sequence.AddStdInitializerListConstructionStep(DestType);
2743 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00002744}
2745
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002746static OverloadingResult
2747ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2748 Expr **Args, unsigned NumArgs,
2749 OverloadCandidateSet &CandidateSet,
2750 DeclContext::lookup_iterator Con,
2751 DeclContext::lookup_iterator ConEnd,
2752 OverloadCandidateSet::iterator &Best,
2753 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00002754 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002755 CandidateSet.clear();
2756
2757 for (; Con != ConEnd; ++Con) {
2758 NamedDecl *D = *Con;
2759 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2760 bool SuppressUserConversions = false;
2761
2762 // Find the constructor (which may be a template).
2763 CXXConstructorDecl *Constructor = 0;
2764 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2765 if (ConstructorTmpl)
2766 Constructor = cast<CXXConstructorDecl>(
2767 ConstructorTmpl->getTemplatedDecl());
2768 else {
2769 Constructor = cast<CXXConstructorDecl>(D);
2770
2771 // If we're performing copy initialization using a copy constructor, we
Sebastian Redlc7b718e2012-02-29 12:47:43 +00002772 // suppress user-defined conversions on the arguments. We do the same for
2773 // move constructors.
2774 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2775 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002776 SuppressUserConversions = true;
2777 }
2778
2779 if (!Constructor->isInvalidDecl() &&
2780 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002781 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002782 if (ConstructorTmpl)
2783 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2784 /*ExplicitArgs*/ 0,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00002785 llvm::makeArrayRef(Args, NumArgs),
2786 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00002787 else {
2788 // C++ [over.match.copy]p1:
2789 // - When initializing a temporary to be bound to the first parameter
2790 // of a constructor that takes a reference to possibly cv-qualified
2791 // T as its first argument, called with a single argument in the
2792 // context of direct-initialization, explicit conversion functions
2793 // are also considered.
2794 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2795 NumArgs == 1 &&
2796 Constructor->isCopyOrMoveConstructor();
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002797 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002798 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00002799 SuppressUserConversions,
2800 /*PartialOverloading=*/false,
2801 /*AllowExplicit=*/AllowExplicitConv);
2802 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002803 }
2804 }
2805
2806 // Perform overload resolution and return the result.
2807 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2808}
2809
Sebastian Redled2e5322011-12-22 14:44:04 +00002810/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2811/// enumerates the constructors of the initialized entity and performs overload
2812/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00002813/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00002814/// class type.
2815static void TryConstructorInitialization(Sema &S,
2816 const InitializedEntity &Entity,
2817 const InitializationKind &Kind,
2818 Expr **Args, unsigned NumArgs,
2819 QualType DestType,
2820 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00002821 bool InitListSyntax = false) {
2822 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2823 "InitListSyntax must come with a single initializer list argument.");
2824
Sebastian Redled2e5322011-12-22 14:44:04 +00002825 // Check constructor arguments for self reference.
2826 if (DeclaratorDecl *DD = Entity.getDecl())
2827 // Parameters arguments are occassionially constructed with itself,
2828 // for instance, in recursive functions. Skip them.
2829 if (!isa<ParmVarDecl>(DD))
2830 for (unsigned i = 0; i < NumArgs; ++i)
2831 S.CheckSelfReference(DD, Args[i]);
2832
Sebastian Redled2e5322011-12-22 14:44:04 +00002833 // The type we're constructing needs to be complete.
2834 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00002835 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002836 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00002837 }
2838
2839 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2840 assert(DestRecordType && "Constructor initialization requires record type");
2841 CXXRecordDecl *DestRecordDecl
2842 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2843
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002844 // Build the candidate set directly in the initialization sequence
2845 // structure, so that it will persist if we fail.
2846 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2847
2848 // Determine whether we are allowed to call explicit constructors or
2849 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00002850 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002851 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00002852
Sebastian Redled2e5322011-12-22 14:44:04 +00002853 // - Otherwise, if T is a class type, constructors are considered. The
2854 // applicable constructors are enumerated, and the best one is chosen
2855 // through overload resolution.
Sebastian Redlab3f7a42012-02-04 21:27:39 +00002856 DeclContext::lookup_iterator ConStart, ConEnd;
2857 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00002858
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002859 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00002860 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002861 bool AsInitializerList = false;
2862
2863 // C++11 [over.match.list]p1:
2864 // When objects of non-aggregate type T are list-initialized, overload
2865 // resolution selects the constructor in two phases:
2866 // - Initially, the candidate functions are the initializer-list
2867 // constructors of the class T and the argument list consists of the
2868 // initializer list as a single argument.
2869 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00002870 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002871 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00002872
2873 // If the initializer list has no elements and T has a default constructor,
2874 // the first phase is omitted.
2875 if (ILE->getNumInits() != 0 ||
2876 (!DestRecordDecl->hasDeclaredDefaultConstructor() &&
2877 !DestRecordDecl->needsImplicitDefaultConstructor()))
2878 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2879 CandidateSet, ConStart, ConEnd, Best,
2880 CopyInitialization, AllowExplicit,
2881 /*OnlyListConstructor=*/true,
2882 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002883
2884 // Time to unwrap the init list.
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002885 Args = ILE->getInits();
2886 NumArgs = ILE->getNumInits();
2887 }
2888
2889 // C++11 [over.match.list]p1:
2890 // - If no viable initializer-list constructor is found, overload resolution
2891 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00002892 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002893 // elements of the initializer list.
2894 if (Result == OR_No_Viable_Function) {
2895 AsInitializerList = false;
2896 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2897 CandidateSet, ConStart, ConEnd, Best,
2898 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00002899 /*OnlyListConstructors=*/false,
2900 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002901 }
2902 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00002903 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002904 InitializationSequence::FK_ListConstructorOverloadFailed :
2905 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002906 Result);
2907 return;
2908 }
2909
Richard Smithd86812d2012-07-05 08:39:21 +00002910 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00002911 // If a program calls for the default initialization of an object
2912 // of a const-qualified type T, T shall be a class type with a
2913 // user-provided default constructor.
2914 if (Kind.getKind() == InitializationKind::IK_Default &&
2915 Entity.getType().isConstQualified() &&
2916 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2917 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2918 return;
2919 }
2920
Sebastian Redl048a6d72012-04-01 19:54:59 +00002921 // C++11 [over.match.list]p1:
2922 // In copy-list-initialization, if an explicit constructor is chosen, the
2923 // initializer is ill-formed.
2924 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2925 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2926 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2927 return;
2928 }
2929
Sebastian Redled2e5322011-12-22 14:44:04 +00002930 // Add the constructor initialization step. Any cv-qualification conversion is
2931 // subsumed by the initialization.
2932 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00002933 Sequence.AddConstructorInitializationStep(CtorDecl,
2934 Best->FoundDecl.getAccess(),
2935 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002936 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00002937}
2938
Sebastian Redl29526f02011-11-27 16:50:07 +00002939static bool
2940ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2941 Expr *Initializer,
2942 QualType &SourceType,
2943 QualType &UnqualifiedSourceType,
2944 QualType UnqualifiedTargetType,
2945 InitializationSequence &Sequence) {
2946 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2947 S.Context.OverloadTy) {
2948 DeclAccessPair Found;
2949 bool HadMultipleCandidates = false;
2950 if (FunctionDecl *Fn
2951 = S.ResolveAddressOfOverloadedFunction(Initializer,
2952 UnqualifiedTargetType,
2953 false, Found,
2954 &HadMultipleCandidates)) {
2955 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2956 HadMultipleCandidates);
2957 SourceType = Fn->getType();
2958 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2959 } else if (!UnqualifiedTargetType->isRecordType()) {
2960 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2961 return true;
2962 }
2963 }
2964 return false;
2965}
2966
2967static void TryReferenceInitializationCore(Sema &S,
2968 const InitializedEntity &Entity,
2969 const InitializationKind &Kind,
2970 Expr *Initializer,
2971 QualType cv1T1, QualType T1,
2972 Qualifiers T1Quals,
2973 QualType cv2T2, QualType T2,
2974 Qualifiers T2Quals,
2975 InitializationSequence &Sequence);
2976
Richard Smithd86812d2012-07-05 08:39:21 +00002977static void TryValueInitialization(Sema &S,
2978 const InitializedEntity &Entity,
2979 const InitializationKind &Kind,
2980 InitializationSequence &Sequence,
2981 InitListExpr *InitList = 0);
2982
Sebastian Redl29526f02011-11-27 16:50:07 +00002983static void TryListInitialization(Sema &S,
2984 const InitializedEntity &Entity,
2985 const InitializationKind &Kind,
2986 InitListExpr *InitList,
2987 InitializationSequence &Sequence);
2988
2989/// \brief Attempt list initialization of a reference.
2990static void TryReferenceListInitialization(Sema &S,
2991 const InitializedEntity &Entity,
2992 const InitializationKind &Kind,
2993 InitListExpr *InitList,
2994 InitializationSequence &Sequence)
2995{
2996 // First, catch C++03 where this isn't possible.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002997 if (!S.getLangOpts().CPlusPlus0x) {
Sebastian Redl29526f02011-11-27 16:50:07 +00002998 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2999 return;
3000 }
3001
3002 QualType DestType = Entity.getType();
3003 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3004 Qualifiers T1Quals;
3005 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3006
3007 // Reference initialization via an initializer list works thus:
3008 // If the initializer list consists of a single element that is
3009 // reference-related to the referenced type, bind directly to that element
3010 // (possibly creating temporaries).
3011 // Otherwise, initialize a temporary with the initializer list and
3012 // bind to that.
3013 if (InitList->getNumInits() == 1) {
3014 Expr *Initializer = InitList->getInit(0);
3015 QualType cv2T2 = Initializer->getType();
3016 Qualifiers T2Quals;
3017 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3018
3019 // If this fails, creating a temporary wouldn't work either.
3020 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3021 T1, Sequence))
3022 return;
3023
3024 SourceLocation DeclLoc = Initializer->getLocStart();
3025 bool dummy1, dummy2, dummy3;
3026 Sema::ReferenceCompareResult RefRelationship
3027 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3028 dummy2, dummy3);
3029 if (RefRelationship >= Sema::Ref_Related) {
3030 // Try to bind the reference here.
3031 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3032 T1Quals, cv2T2, T2, T2Quals, Sequence);
3033 if (Sequence)
3034 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3035 return;
3036 }
3037 }
3038
3039 // Not reference-related. Create a temporary and bind to that.
3040 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3041
3042 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3043 if (Sequence) {
3044 if (DestType->isRValueReferenceType() ||
3045 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3046 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3047 else
3048 Sequence.SetFailed(
3049 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3050 }
3051}
3052
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003053/// \brief Attempt list initialization (C++0x [dcl.init.list])
3054static void TryListInitialization(Sema &S,
3055 const InitializedEntity &Entity,
3056 const InitializationKind &Kind,
3057 InitListExpr *InitList,
3058 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003059 QualType DestType = Entity.getType();
3060
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003061 // C++ doesn't allow scalar initialization with more than one argument.
3062 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003063 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003064 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3065 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3066 return;
3067 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003068 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003069 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003070 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003071 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003072 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003073 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003074 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003075 return;
3076 }
3077
Richard Smithd86812d2012-07-05 08:39:21 +00003078 // C++11 [dcl.init.list]p3:
3079 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003080 if (!DestType->isAggregateType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003081 if (S.getLangOpts().CPlusPlus0x) {
Richard Smithd86812d2012-07-05 08:39:21 +00003082 // - Otherwise, if the initializer list has no elements and T is a
3083 // class type with a default constructor, the object is
3084 // value-initialized.
3085 if (InitList->getNumInits() == 0) {
3086 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3087 if (RD->hasDeclaredDefaultConstructor() ||
3088 RD->needsImplicitDefaultConstructor()) {
3089 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3090 return;
3091 }
3092 }
3093
3094 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3095 // an initializer_list object constructed [...]
3096 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3097 return;
3098
3099 // - Otherwise, if T is a class type, constructors are considered.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003100 Expr *Arg = InitList;
Richard Smithd86812d2012-07-05 08:39:21 +00003101 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3102 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003103 } else
3104 Sequence.SetFailed(
3105 InitializationSequence::FK_InitListBadDestinationType);
3106 return;
3107 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003108 }
3109
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003110 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003111 DestType, /*VerifyOnly=*/true,
Sebastian Redl5a41f682012-02-12 16:37:24 +00003112 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003113 !S.getLangOpts().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003114 if (CheckInitList.HadError()) {
3115 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3116 return;
3117 }
3118
3119 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003120 Sequence.AddListInitializationStep(DestType);
3121}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122
3123/// \brief Try a reference initialization that involves calling a conversion
3124/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003125static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3126 const InitializedEntity &Entity,
3127 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003128 Expr *Initializer,
3129 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003131 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003132 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3133 QualType T1 = cv1T1.getUnqualifiedType();
3134 QualType cv2T2 = Initializer->getType();
3135 QualType T2 = cv2T2.getUnqualifiedType();
3136
3137 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003138 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003139 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003141 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003142 ObjCConversion,
3143 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003145 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003146 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003147 (void)ObjCLifetimeConversion;
3148
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003149 // Build the candidate set directly in the initialization sequence
3150 // structure, so that it will persist if we fail.
3151 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3152 CandidateSet.clear();
3153
3154 // Determine whether we are allowed to call explicit constructors or
3155 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003156 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregor6073dca2012-02-24 23:56:31 +00003157 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3158
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003160 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3161 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003162 // The type we're converting to is a class type. Enumerate its constructors
3163 // to see if there is a suitable conversion.
3164 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003165
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003167 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003168 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003169 NamedDecl *D = *Con;
3170 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3171
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 // Find the constructor (which may be a template).
3173 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003174 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003175 if (ConstructorTmpl)
3176 Constructor = cast<CXXConstructorDecl>(
3177 ConstructorTmpl->getTemplatedDecl());
3178 else
John McCalla0296f72010-03-19 07:35:19 +00003179 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003181 if (!Constructor->isInvalidDecl() &&
3182 Constructor->isConvertingConstructor(AllowExplicit)) {
3183 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003184 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003185 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003186 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003187 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188 else
John McCalla0296f72010-03-19 07:35:19 +00003189 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003190 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003191 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003194 }
John McCall3696dcb2010-08-17 07:23:57 +00003195 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3196 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003197
Douglas Gregor496e8b342010-05-07 19:42:26 +00003198 const RecordType *T2RecordType = 0;
3199 if ((T2RecordType = T2->getAs<RecordType>()) &&
3200 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 // The type we're converting from is a class type, enumerate its conversion
3202 // functions.
3203 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3204
John McCallad371252010-01-20 00:46:10 +00003205 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003206 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003207 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3208 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003209 NamedDecl *D = *I;
3210 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3211 if (isa<UsingShadowDecl>(D))
3212 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003214 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3215 CXXConversionDecl *Conv;
3216 if (ConvTemplate)
3217 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3218 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003219 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003221 // If the conversion function doesn't return a reference type,
3222 // it can't be considered for this conversion unless we're allowed to
3223 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224 // FIXME: Do we need to make sure that we only consider conversion
3225 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003227 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3229 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003230 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003231 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003232 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003233 else
John McCalla0296f72010-03-19 07:35:19 +00003234 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003235 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003236 }
3237 }
3238 }
John McCall3696dcb2010-08-17 07:23:57 +00003239 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3240 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003242 SourceLocation DeclLoc = Initializer->getLocStart();
3243
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003245 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003247 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003248 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003251
Chandler Carruth30141632011-02-25 19:41:05 +00003252 // This is the overload that will actually be used for the initialization, so
3253 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003254 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003255
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003256 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003257 if (isa<CXXConversionDecl>(Function))
3258 T2 = Function->getResultType();
3259 else
3260 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003261
3262 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003263 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003264 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003265 T2.getNonLValueExprType(S.Context),
3266 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003267
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003269 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003270 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003271 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003272 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003273 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003274 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003276 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003277 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003278 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003281 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003282 NewDerivedToBase, NewObjCConversion,
3283 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003284 if (NewRefRelationship == Sema::Ref_Incompatible) {
3285 // If the type we've converted to is not reference-related to the
3286 // type we're looking for, then there is another conversion step
3287 // we need to perform to produce a temporary of the right type
3288 // that we'll be binding to.
3289 ImplicitConversionSequence ICS;
3290 ICS.setStandard();
3291 ICS.Standard = Best->FinalConversion;
3292 T2 = ICS.Standard.getToType(2);
3293 Sequence.AddConversionSequenceStep(ICS, T2);
3294 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003295 Sequence.AddDerivedToBaseCastStep(
3296 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003298 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003299 else if (NewObjCConversion)
3300 Sequence.AddObjCObjectConversionStep(
3301 S.Context.getQualifiedType(T1,
3302 T2.getNonReferenceType().getQualifiers()));
3303
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003304 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003305 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003307 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3308 return OR_Success;
3309}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310
Richard Smithc620f552011-10-19 16:55:56 +00003311static void CheckCXX98CompatAccessibleCopy(Sema &S,
3312 const InitializedEntity &Entity,
3313 Expr *CurInitExpr);
3314
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3316static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003317 const InitializedEntity &Entity,
3318 const InitializationKind &Kind,
3319 Expr *Initializer,
3320 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003321 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003322 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003323 Qualifiers T1Quals;
3324 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003325 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003326 Qualifiers T2Quals;
3327 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003328
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 // If the initializer is the address of an overloaded function, try
3330 // to resolve the overloaded function. If all goes well, T2 is the
3331 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003332 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3333 T1, Sequence))
3334 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003335
Sebastian Redl29526f02011-11-27 16:50:07 +00003336 // Delegate everything else to a subfunction.
3337 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3338 T1Quals, cv2T2, T2, T2Quals, Sequence);
3339}
3340
3341/// \brief Reference initialization without resolving overloaded functions.
3342static void TryReferenceInitializationCore(Sema &S,
3343 const InitializedEntity &Entity,
3344 const InitializationKind &Kind,
3345 Expr *Initializer,
3346 QualType cv1T1, QualType T1,
3347 Qualifiers T1Quals,
3348 QualType cv2T2, QualType T2,
3349 Qualifiers T2Quals,
3350 InitializationSequence &Sequence) {
3351 QualType DestType = Entity.getType();
3352 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003353 // Compute some basic properties of the types and the initializer.
3354 bool isLValueRef = DestType->isLValueReferenceType();
3355 bool isRValueRef = !isLValueRef;
3356 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003357 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003358 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003359 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003360 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003361 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003362 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003363
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003364 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003366 // "cv2 T2" as follows:
3367 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003369 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003370 // Note the analogous bullet points for rvlaue refs to functions. Because
3371 // there are no function rvalues in C++, rvalue refs to functions are treated
3372 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003373 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003374 bool T1Function = T1->isFunctionType();
3375 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003377 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003379 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003380 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003381 // reference-compatible with "cv2 T2," or
3382 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003384 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003385 // can occur. However, we do pay attention to whether it is a bit-field
3386 // to decide whether we're actually binding to a temporary created from
3387 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003388 if (DerivedToBase)
3389 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003391 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003392 else if (ObjCConversion)
3393 Sequence.AddObjCObjectConversionStep(
3394 S.Context.getQualifiedType(T1, T2Quals));
3395
Chandler Carruth04bdce62010-01-12 20:32:25 +00003396 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003397 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003398 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003399 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003400 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003401 return;
3402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
3404 // - has a class type (i.e., T2 is a class type), where T1 is not
3405 // reference-related to T2, and can be implicitly converted to an
3406 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3407 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003408 // applicable conversion functions (13.3.1.6) and choosing the best
3409 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003410 // If we have an rvalue ref to function type here, the rhs must be
3411 // an rvalue.
3412 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3413 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003415 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003416 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003417 Sequence);
3418 if (ConvOvlResult == OR_Success)
3419 return;
John McCall0d1da222010-01-12 00:44:57 +00003420 if (ConvOvlResult != OR_No_Viable_Function) {
3421 Sequence.SetOverloadFailure(
3422 InitializationSequence::FK_ReferenceInitOverloadFailed,
3423 ConvOvlResult);
3424 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003425 }
3426 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003427
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003429 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003430 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003431 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003432 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3433 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3434 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003435 Sequence.SetOverloadFailure(
3436 InitializationSequence::FK_ReferenceInitOverloadFailed,
3437 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003438 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003439 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003440 ? (RefRelationship == Sema::Ref_Related
3441 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3442 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3443 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003445 return;
3446 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003447
Douglas Gregor92e460e2011-01-20 16:44:54 +00003448 // - If the initializer expression
3449 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3450 // "cv1 T1" is reference-compatible with "cv2 T2"
3451 // Note: functions are handled below.
3452 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003453 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003455 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003456 (InitCategory.isXValue() ||
3457 (InitCategory.isPRValue() && T2->isRecordType()) ||
3458 (InitCategory.isPRValue() && T2->isArrayType()))) {
3459 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3460 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003461 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3462 // compiler the freedom to perform a copy here or bind to the
3463 // object, while C++0x requires that we bind directly to the
3464 // object. Hence, we always bind to the object without making an
3465 // extra copy. However, in C++03 requires that we check for the
3466 // presence of a suitable copy constructor:
3467 //
3468 // The constructor that would be used to make the copy shall
3469 // be callable whether or not the copy is actually done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003470 if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003471 Sequence.AddExtraneousCopyToTemporary(cv2T2);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003472 else if (S.getLangOpts().CPlusPlus0x)
Richard Smithc620f552011-10-19 16:55:56 +00003473 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregor92e460e2011-01-20 16:44:54 +00003476 if (DerivedToBase)
3477 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3478 ValueKind);
3479 else if (ObjCConversion)
3480 Sequence.AddObjCObjectConversionStep(
3481 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
Douglas Gregor92e460e2011-01-20 16:44:54 +00003483 if (T1Quals != T2Quals)
3484 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003486 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
3490 // - has a class type (i.e., T2 is a class type), where T1 is not
3491 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003492 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3493 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003494 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003495 if (RefRelationship == Sema::Ref_Incompatible) {
3496 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3497 Kind, Initializer,
3498 /*AllowRValues=*/true,
3499 Sequence);
3500 if (ConvOvlResult)
3501 Sequence.SetOverloadFailure(
3502 InitializationSequence::FK_ReferenceInitOverloadFailed,
3503 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003505 return;
3506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003508 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3509 return;
3510 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003511
3512 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003513 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003515 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003516
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003517 // Determine whether we are allowed to call explicit constructors or
3518 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003519 bool AllowExplicit = Kind.AllowExplicit();
John McCallec6f4e92010-06-04 02:29:22 +00003520
3521 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3522
John McCall31168b02011-06-15 23:02:42 +00003523 ImplicitConversionSequence ICS
3524 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003525 /*SuppressUserConversions*/ false,
3526 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003527 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003528 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3529 /*AllowObjCWritebackConversion=*/false);
3530
3531 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 // FIXME: Use the conversion function set stored in ICS to turn
3533 // this into an overloading ambiguity diagnostic. However, we need
3534 // to keep that set as an OverloadCandidateSet rather than as some
3535 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003536 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3537 Sequence.SetOverloadFailure(
3538 InitializationSequence::FK_ReferenceInitOverloadFailed,
3539 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003540 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3541 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003542 else
3543 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003544 return;
John McCall31168b02011-06-15 23:02:42 +00003545 } else {
3546 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547 }
3548
3549 // [...] If T1 is reference-related to T2, cv1 must be the
3550 // same cv-qualification as, or greater cv-qualification
3551 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003552 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3553 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003555 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003556 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3557 return;
3558 }
3559
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003561 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003563 InitCategory.isLValue()) {
3564 Sequence.SetFailed(
3565 InitializationSequence::FK_RValueReferenceBindingToLValue);
3566 return;
3567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003569 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3570 return;
3571}
3572
3573/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574/// (C++ [dcl.init.string], C99 6.7.8).
3575static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003576 const InitializedEntity &Entity,
3577 const InitializationKind &Kind,
3578 Expr *Initializer,
3579 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003580 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003581}
3582
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003583/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003585 const InitializedEntity &Entity,
3586 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00003587 InitializationSequence &Sequence,
3588 InitListExpr *InitList) {
3589 assert((!InitList || InitList->getNumInits() == 0) &&
3590 "Shouldn't use value-init for non-empty init lists");
3591
Richard Smith1bfe0682012-02-14 21:14:13 +00003592 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003593 //
3594 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003595 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003597 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003598 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003600 if (const RecordType *RT = T->getAs<RecordType>()) {
3601 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00003602 bool NeedZeroInitialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003603 if (!S.getLangOpts().CPlusPlus0x) {
Richard Smithd86812d2012-07-05 08:39:21 +00003604 // C++98:
3605 // -- if T is a class type (clause 9) with a user-declared constructor
3606 // (12.1), then the default constructor for T is called (and the
3607 // initialization is ill-formed if T has no accessible default
3608 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003609 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00003610 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003611 } else {
3612 // C++11:
3613 // -- if T is a class type (clause 9) with either no default constructor
3614 // (12.1 [class.ctor]) or a default constructor that is user-provided
3615 // or deleted, then the object is default-initialized;
3616 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3617 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00003618 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003620
Richard Smith1bfe0682012-02-14 21:14:13 +00003621 // -- if T is a (possibly cv-qualified) non-union class type without a
3622 // user-provided or deleted default constructor, then the object is
3623 // zero-initialized and, if T has a non-trivial default constructor,
3624 // default-initialized;
Richard Smithe2648ba2012-05-07 01:07:30 +00003625 // FIXME: The 'non-union' here is a defect (not yet assigned an issue
3626 // number). Update the quotation when the defect is resolved.
Richard Smithd86812d2012-07-05 08:39:21 +00003627 if (NeedZeroInitialization)
3628 Sequence.AddZeroInitializationStep(Entity.getType());
3629
3630 // If this is list-value-initialization, pass the empty init list on when
3631 // building the constructor call. This affects the semantics of a few
3632 // things (such as whether an explicit default constructor can be called).
3633 Expr *InitListAsExpr = InitList;
3634 Expr **Args = InitList ? &InitListAsExpr : 0;
3635 unsigned NumArgs = InitList ? 1 : 0;
3636 bool InitListSyntax = InitList;
3637
3638 return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3639 Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003640 }
3641 }
3642
Douglas Gregor1b303932009-12-22 15:35:07 +00003643 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003644}
3645
Douglas Gregor85dabae2009-12-16 01:38:02 +00003646/// \brief Attempt default initialization (C++ [dcl.init]p6).
3647static void TryDefaultInitialization(Sema &S,
3648 const InitializedEntity &Entity,
3649 const InitializationKind &Kind,
3650 InitializationSequence &Sequence) {
3651 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652
Douglas Gregor85dabae2009-12-16 01:38:02 +00003653 // C++ [dcl.init]p6:
3654 // To default-initialize an object of type T means:
3655 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003656 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3657
Douglas Gregor85dabae2009-12-16 01:38:02 +00003658 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3659 // constructor for T is called (and the initialization is ill-formed if
3660 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003661 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003662 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3663 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665
Douglas Gregor85dabae2009-12-16 01:38:02 +00003666 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Douglas Gregor85dabae2009-12-16 01:38:02 +00003668 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003670 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003671 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003672 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003673 return;
3674 }
3675
3676 // If the destination type has a lifetime property, zero-initialize it.
3677 if (DestType.getQualifiers().hasObjCLifetime()) {
3678 Sequence.AddZeroInitializationStep(Entity.getType());
3679 return;
3680 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003681}
3682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3684/// which enumerates all conversion functions and performs overload resolution
3685/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003687 const InitializedEntity &Entity,
3688 const InitializationKind &Kind,
3689 Expr *Initializer,
3690 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003691 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003692 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3693 QualType SourceType = Initializer->getType();
3694 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3695 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696
Douglas Gregor540c3b02009-12-14 17:27:33 +00003697 // Build the candidate set directly in the initialization sequence
3698 // structure, so that it will persist if we fail.
3699 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3700 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregor540c3b02009-12-14 17:27:33 +00003702 // Determine whether we are allowed to call explicit constructors or
3703 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003704 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705
Douglas Gregor540c3b02009-12-14 17:27:33 +00003706 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3707 // The type we're converting to is a class type. Enumerate its constructors
3708 // to see if there is a suitable conversion.
3709 CXXRecordDecl *DestRecordDecl
3710 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711
Douglas Gregord9848152010-04-26 14:36:57 +00003712 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003714 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003715 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003716 Con != ConEnd; ++Con) {
3717 NamedDecl *D = *Con;
3718 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Douglas Gregord9848152010-04-26 14:36:57 +00003720 // Find the constructor (which may be a template).
3721 CXXConstructorDecl *Constructor = 0;
3722 FunctionTemplateDecl *ConstructorTmpl
3723 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003724 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003725 Constructor = cast<CXXConstructorDecl>(
3726 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003727 else
Douglas Gregord9848152010-04-26 14:36:57 +00003728 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Douglas Gregord9848152010-04-26 14:36:57 +00003730 if (!Constructor->isInvalidDecl() &&
3731 Constructor->isConvertingConstructor(AllowExplicit)) {
3732 if (ConstructorTmpl)
3733 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3734 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003735 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003736 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003737 else
3738 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003739 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003740 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742 }
Douglas Gregord9848152010-04-26 14:36:57 +00003743 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003744 }
Eli Friedman78275202009-12-19 08:11:05 +00003745
3746 SourceLocation DeclLoc = Initializer->getLocStart();
3747
Douglas Gregor540c3b02009-12-14 17:27:33 +00003748 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3749 // The type we're converting from is a class type, enumerate its conversion
3750 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003751
Eli Friedman4afe9a32009-12-20 22:12:03 +00003752 // We can only enumerate the conversion functions for a complete type; if
3753 // the type isn't complete, simply skip this step.
3754 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3755 CXXRecordDecl *SourceRecordDecl
3756 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757
John McCallad371252010-01-20 00:46:10 +00003758 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003759 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003760 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003762 I != E; ++I) {
3763 NamedDecl *D = *I;
3764 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3765 if (isa<UsingShadowDecl>(D))
3766 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
Eli Friedman4afe9a32009-12-20 22:12:03 +00003768 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3769 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003770 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003771 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003772 else
John McCallda4458e2010-03-31 01:36:47 +00003773 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Eli Friedman4afe9a32009-12-20 22:12:03 +00003775 if (AllowExplicit || !Conv->isExplicit()) {
3776 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003777 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003778 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003779 CandidateSet);
3780 else
John McCalla0296f72010-03-19 07:35:19 +00003781 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003782 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003783 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003784 }
3785 }
3786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
3788 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003789 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003790 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003791 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003792 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003794 Result);
3795 return;
3796 }
John McCall0d1da222010-01-12 00:44:57 +00003797
Douglas Gregor540c3b02009-12-14 17:27:33 +00003798 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003799 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003800 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003801
Douglas Gregor540c3b02009-12-14 17:27:33 +00003802 if (isa<CXXConstructorDecl>(Function)) {
3803 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00003804 // subsumed by the initialization. Per DR5, the created temporary is of the
3805 // cv-unqualified type of the destination.
3806 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3807 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003808 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003809 return;
3810 }
3811
3812 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003813 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003814 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00003815 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00003816 // the resulting temporary object (possible to create an object of
3817 // a base class type). That copy is not a separate conversion, so
3818 // we just make a note of the actual destination type (possibly a
3819 // base class of the type returned by the conversion function) and
3820 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003821 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3822 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003823 return;
3824 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003825
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003826 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3827 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828
Douglas Gregor5ab11652010-04-17 22:01:05 +00003829 // If the conversion following the call to the conversion function
3830 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003831 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3832 Best->FinalConversion.Third) {
3833 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003834 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003835 ICS.Standard = Best->FinalConversion;
3836 Sequence.AddConversionSequenceStep(ICS, DestType);
3837 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003838}
3839
John McCall31168b02011-06-15 23:02:42 +00003840/// The non-zero enum values here are indexes into diagnostic alternatives.
3841enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3842
3843/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003844static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3845 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003846 // Skip parens.
3847 e = e->IgnoreParens();
3848
3849 // Skip address-of nodes.
3850 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3851 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003852 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003853
3854 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003855 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3856 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003857 case CK_Dependent:
3858 case CK_BitCast:
3859 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003860 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003861 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003862
3863 case CK_ArrayToPointerDecay:
3864 return IIK_nonscalar;
3865
3866 case CK_NullToPointer:
3867 return IIK_okay;
3868
3869 default:
3870 break;
3871 }
3872
3873 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00003874 } else if (isa<DeclRefExpr>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003875 if (!isAddressOf) return IIK_nonlocal;
3876
John McCall113bee02012-03-10 09:33:50 +00003877 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3878 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00003879
3880 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003881
3882 // If we have a conditional operator, check both sides.
3883 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003884 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003885 return iik;
3886
John McCall63f84442011-06-27 23:59:58 +00003887 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003888
3889 // These are never scalar.
3890 } else if (isa<ArraySubscriptExpr>(e)) {
3891 return IIK_nonscalar;
3892
3893 // Otherwise, it needs to be a null pointer constant.
3894 } else {
3895 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3896 ? IIK_okay : IIK_nonlocal);
3897 }
3898
3899 return IIK_nonlocal;
3900}
3901
3902/// Check whether the given expression is a valid operand for an
3903/// indirect copy/restore.
3904static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3905 assert(src->isRValue());
3906
John McCall63f84442011-06-27 23:59:58 +00003907 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003908 if (iik == IIK_okay) return;
3909
3910 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3911 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3912 << src->getSourceRange();
3913}
3914
Douglas Gregore2f943b2011-02-22 18:29:51 +00003915/// \brief Determine whether we have compatible array types for the
3916/// purposes of GNU by-copy array initialization.
3917static bool hasCompatibleArrayTypes(ASTContext &Context,
3918 const ArrayType *Dest,
3919 const ArrayType *Source) {
3920 // If the source and destination array types are equivalent, we're
3921 // done.
3922 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3923 return true;
3924
3925 // Make sure that the element types are the same.
3926 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3927 return false;
3928
3929 // The only mismatch we allow is when the destination is an
3930 // incomplete array type and the source is a constant array type.
3931 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3932}
3933
John McCall31168b02011-06-15 23:02:42 +00003934static bool tryObjCWritebackConversion(Sema &S,
3935 InitializationSequence &Sequence,
3936 const InitializedEntity &Entity,
3937 Expr *Initializer) {
3938 bool ArrayDecay = false;
3939 QualType ArgType = Initializer->getType();
3940 QualType ArgPointee;
3941 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3942 ArrayDecay = true;
3943 ArgPointee = ArgArrayType->getElementType();
3944 ArgType = S.Context.getPointerType(ArgPointee);
3945 }
3946
3947 // Handle write-back conversion.
3948 QualType ConvertedArgType;
3949 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3950 ConvertedArgType))
3951 return false;
3952
3953 // We should copy unless we're passing to an argument explicitly
3954 // marked 'out'.
3955 bool ShouldCopy = true;
3956 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3957 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3958
3959 // Do we need an lvalue conversion?
3960 if (ArrayDecay || Initializer->isGLValue()) {
3961 ImplicitConversionSequence ICS;
3962 ICS.setStandard();
3963 ICS.Standard.setAsIdentityConversion();
3964
3965 QualType ResultType;
3966 if (ArrayDecay) {
3967 ICS.Standard.First = ICK_Array_To_Pointer;
3968 ResultType = S.Context.getPointerType(ArgPointee);
3969 } else {
3970 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3971 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3972 }
3973
3974 Sequence.AddConversionSequenceStep(ICS, ResultType);
3975 }
3976
3977 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3978 return true;
3979}
3980
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003981InitializationSequence::InitializationSequence(Sema &S,
3982 const InitializedEntity &Entity,
3983 const InitializationKind &Kind,
3984 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003985 unsigned NumArgs)
3986 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003987 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003989 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003990 // The semantics of initializers are as follows. The destination type is
3991 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003992 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003994 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003995 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003996
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003997 if (DestType->isDependentType() ||
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003998 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003999 SequenceKind = DependentSequence;
4000 return;
4001 }
4002
Sebastian Redld201edf2011-06-05 13:59:11 +00004003 // Almost everything is a normal sequence.
4004 setSequenceKind(NormalSequence);
4005
John McCalled75c092010-12-07 22:54:16 +00004006 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00004007 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00004008 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00004009 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4010 if (result.isInvalid()) {
4011 SetFailed(FK_PlaceholderType);
4012 return;
John McCall4124c492011-10-17 18:40:02 +00004013 }
John McCalld5c98ae2011-11-15 01:35:18 +00004014 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00004015 }
John McCalled75c092010-12-07 22:54:16 +00004016
John McCall4124c492011-10-17 18:40:02 +00004017
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004018 QualType SourceType;
4019 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004020 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004021 Initializer = Args[0];
4022 if (!isa<InitListExpr>(Initializer))
4023 SourceType = Initializer->getType();
4024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025
Sebastian Redl0501c632012-02-12 16:37:36 +00004026 // - If the initializer is a (non-parenthesized) braced-init-list, the
4027 // object is list-initialized (8.5.4).
4028 if (Kind.getKind() != InitializationKind::IK_Direct) {
4029 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4030 TryListInitialization(S, Entity, Kind, InitList, *this);
4031 return;
4032 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004035 // - If the destination type is a reference type, see 8.5.3.
4036 if (DestType->isReferenceType()) {
4037 // C++0x [dcl.init.ref]p1:
4038 // A variable declared to be a T& or T&&, that is, "reference to type T"
4039 // (8.3.2), shall be initialized by an object, or function, of type T or
4040 // by an object that can be converted into a T.
4041 // (Therefore, multiple arguments are not permitted.)
4042 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004043 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004044 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004045 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046 return;
4047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004048
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004050 if (Kind.getKind() == InitializationKind::IK_Value ||
4051 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004052 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 return;
4054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Douglas Gregor85dabae2009-12-16 01:38:02 +00004056 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004057 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004058 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004059 return;
4060 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004061
John McCall66884dd2011-02-21 07:22:22 +00004062 // - If the destination type is an array of characters, an array of
4063 // char16_t, an array of char32_t, or an array of wchar_t, and the
4064 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004066 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004067 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004068 if (Initializer && isa<VariableArrayType>(DestAT)) {
4069 SetFailed(FK_VariableLengthArrayHasInitializer);
4070 return;
4071 }
4072
Douglas Gregore2f943b2011-02-22 18:29:51 +00004073 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004074 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004075 return;
4076 }
4077
Douglas Gregore2f943b2011-02-22 18:29:51 +00004078 // Note: as an GNU C extension, we allow initialization of an
4079 // array from a compound literal that creates an array of the same
4080 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004081 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004082 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4083 Initializer->getType()->isArrayType()) {
4084 const ArrayType *SourceAT
4085 = Context.getAsArrayType(Initializer->getType());
4086 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004087 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004088 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004089 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004090 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004091 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004092 }
Richard Smithebeed412012-02-15 22:38:09 +00004093 }
Richard Smithd86812d2012-07-05 08:39:21 +00004094 // Note: as a GNU C++ extension, we allow list-initialization of a
4095 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004096 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004097 Entity.getKind() == InitializedEntity::EK_Member &&
4098 Initializer && isa<InitListExpr>(Initializer)) {
4099 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4100 *this);
4101 AddParenthesizedArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004102 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004103 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004104 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004105 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004107 return;
4108 }
Eli Friedman78275202009-12-19 08:11:05 +00004109
John McCall31168b02011-06-15 23:02:42 +00004110 // Determine whether we should consider writeback conversions for
4111 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004112 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004113 Entity.getKind() == InitializedEntity::EK_Parameter;
4114
4115 // We're at the end of the line for C: it's either a write-back conversion
4116 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004117 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004118 // If allowed, check whether this is an Objective-C writeback conversion.
4119 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004120 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004121 return;
4122 }
4123
4124 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004125 AddCAssignmentStep(DestType);
4126 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004127 return;
4128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004129
David Blaikiebbafb8a2012-03-11 07:00:24 +00004130 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004131
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004132 // - If the destination type is a (possibly cv-qualified) class type:
4133 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134 // - If the initialization is direct-initialization, or if it is
4135 // copy-initialization where the cv-unqualified version of the
4136 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004137 // class of the destination, constructors are considered. [...]
4138 if (Kind.getKind() == InitializationKind::IK_Direct ||
4139 (Kind.getKind() == InitializationKind::IK_Copy &&
4140 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4141 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004143 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004145 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004147 // used) to a derived class thereof are enumerated as described in
4148 // 13.3.1.4, and the best one is chosen through overload resolution
4149 // (13.3).
4150 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004151 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152 return;
4153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
Douglas Gregor85dabae2009-12-16 01:38:02 +00004155 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004156 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004157 return;
4158 }
4159 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
4161 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004162 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004163 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004164 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4165 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004166 return;
4167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004169 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004170 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004171 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004173 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004174
4175 ImplicitConversionSequence ICS
4176 = S.TryImplicitConversion(Initializer, Entity.getType(),
4177 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004178 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004179 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004180 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4181 allowObjCWritebackConversion);
4182
4183 if (ICS.isStandard() &&
4184 ICS.Standard.Second == ICK_Writeback_Conversion) {
4185 // Objective-C ARC writeback conversion.
4186
4187 // We should copy unless we're passing to an argument explicitly
4188 // marked 'out'.
4189 bool ShouldCopy = true;
4190 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4191 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4192
4193 // If there was an lvalue adjustment, add it as a separate conversion.
4194 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4195 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4196 ImplicitConversionSequence LvalueICS;
4197 LvalueICS.setStandard();
4198 LvalueICS.Standard.setAsIdentityConversion();
4199 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4200 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004201 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004202 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004203
4204 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004205 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004206 DeclAccessPair dap;
4207 if (Initializer->getType() == Context.OverloadTy &&
4208 !S.ResolveAddressOfOverloadedFunction(Initializer
4209 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004210 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004211 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004212 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004213 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004214 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004215
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004216 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004217 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004218}
4219
4220InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004221 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222 StepEnd = Steps.end();
4223 Step != StepEnd; ++Step)
4224 Step->Destroy();
4225}
4226
4227//===----------------------------------------------------------------------===//
4228// Perform initialization
4229//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004231getAssignmentAction(const InitializedEntity &Entity) {
4232 switch(Entity.getKind()) {
4233 case InitializedEntity::EK_Variable:
4234 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004235 case InitializedEntity::EK_Exception:
4236 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004237 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004238 return Sema::AA_Initializing;
4239
4240 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004242 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4243 return Sema::AA_Sending;
4244
Douglas Gregore1314a62009-12-18 05:02:21 +00004245 return Sema::AA_Passing;
4246
4247 case InitializedEntity::EK_Result:
4248 return Sema::AA_Returning;
4249
Douglas Gregore1314a62009-12-18 05:02:21 +00004250 case InitializedEntity::EK_Temporary:
4251 // FIXME: Can we tell apart casting vs. converting?
4252 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253
Douglas Gregore1314a62009-12-18 05:02:21 +00004254 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004255 case InitializedEntity::EK_ArrayElement:
4256 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004257 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004258 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004259 case InitializedEntity::EK_LambdaCapture:
Douglas Gregore1314a62009-12-18 05:02:21 +00004260 return Sema::AA_Initializing;
4261 }
4262
David Blaikie8a40f702012-01-17 06:56:22 +00004263 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004264}
4265
Douglas Gregor95562572010-04-24 23:45:46 +00004266/// \brief Whether we should binding a created object as a temporary when
4267/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004268static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004269 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004270 case InitializedEntity::EK_ArrayElement:
4271 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004272 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004273 case InitializedEntity::EK_New:
4274 case InitializedEntity::EK_Variable:
4275 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004276 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004277 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004278 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004279 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004280 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004281 case InitializedEntity::EK_LambdaCapture:
Douglas Gregore1314a62009-12-18 05:02:21 +00004282 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283
Douglas Gregore1314a62009-12-18 05:02:21 +00004284 case InitializedEntity::EK_Parameter:
4285 case InitializedEntity::EK_Temporary:
4286 return true;
4287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregore1314a62009-12-18 05:02:21 +00004289 llvm_unreachable("missed an InitializedEntity kind?");
4290}
4291
Douglas Gregor95562572010-04-24 23:45:46 +00004292/// \brief Whether the given entity, when initialized with an object
4293/// created for that initialization, requires destruction.
4294static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4295 switch (Entity.getKind()) {
4296 case InitializedEntity::EK_Member:
4297 case InitializedEntity::EK_Result:
4298 case InitializedEntity::EK_New:
4299 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004300 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004301 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004302 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004303 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004304 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004305 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregor95562572010-04-24 23:45:46 +00004307 case InitializedEntity::EK_Variable:
4308 case InitializedEntity::EK_Parameter:
4309 case InitializedEntity::EK_Temporary:
4310 case InitializedEntity::EK_ArrayElement:
4311 case InitializedEntity::EK_Exception:
4312 return true;
4313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
4315 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004316}
4317
Richard Smithc620f552011-10-19 16:55:56 +00004318/// \brief Look for copy and move constructors and constructor templates, for
4319/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4320static void LookupCopyAndMoveConstructors(Sema &S,
4321 OverloadCandidateSet &CandidateSet,
4322 CXXRecordDecl *Class,
4323 Expr *CurInitExpr) {
4324 DeclContext::lookup_iterator Con, ConEnd;
4325 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4326 Con != ConEnd; ++Con) {
4327 CXXConstructorDecl *Constructor = 0;
4328
4329 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4330 // Handle copy/moveconstructors, only.
4331 if (!Constructor || Constructor->isInvalidDecl() ||
4332 !Constructor->isCopyOrMoveConstructor() ||
4333 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4334 continue;
4335
4336 DeclAccessPair FoundDecl
4337 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4338 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004339 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004340 continue;
4341 }
4342
4343 // Handle constructor templates.
4344 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4345 if (ConstructorTmpl->isInvalidDecl())
4346 continue;
4347
4348 Constructor = cast<CXXConstructorDecl>(
4349 ConstructorTmpl->getTemplatedDecl());
4350 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4351 continue;
4352
4353 // FIXME: Do we need to limit this to copy-constructor-like
4354 // candidates?
4355 DeclAccessPair FoundDecl
4356 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4357 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004358 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004359 }
4360}
4361
4362/// \brief Get the location at which initialization diagnostics should appear.
4363static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4364 Expr *Initializer) {
4365 switch (Entity.getKind()) {
4366 case InitializedEntity::EK_Result:
4367 return Entity.getReturnLoc();
4368
4369 case InitializedEntity::EK_Exception:
4370 return Entity.getThrowLoc();
4371
4372 case InitializedEntity::EK_Variable:
4373 return Entity.getDecl()->getLocation();
4374
Douglas Gregor19666fb2012-02-15 16:57:26 +00004375 case InitializedEntity::EK_LambdaCapture:
4376 return Entity.getCaptureLoc();
4377
Richard Smithc620f552011-10-19 16:55:56 +00004378 case InitializedEntity::EK_ArrayElement:
4379 case InitializedEntity::EK_Member:
4380 case InitializedEntity::EK_Parameter:
4381 case InitializedEntity::EK_Temporary:
4382 case InitializedEntity::EK_New:
4383 case InitializedEntity::EK_Base:
4384 case InitializedEntity::EK_Delegating:
4385 case InitializedEntity::EK_VectorElement:
4386 case InitializedEntity::EK_ComplexElement:
4387 case InitializedEntity::EK_BlockElement:
4388 return Initializer->getLocStart();
4389 }
4390 llvm_unreachable("missed an InitializedEntity kind?");
4391}
4392
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004393/// \brief Make a (potentially elidable) temporary copy of the object
4394/// provided by the given initializer by calling the appropriate copy
4395/// constructor.
4396///
4397/// \param S The Sema object used for type-checking.
4398///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004399/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004400/// the type of the initializer expression or a superclass thereof.
4401///
James Dennett634962f2012-06-14 21:40:34 +00004402/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004403///
4404/// \param CurInit The initializer expression.
4405///
4406/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4407/// is permitted in C++03 (but not C++0x) when binding a reference to
4408/// an rvalue.
4409///
4410/// \returns An expression that copies the initializer expression into
4411/// a temporary object, or an error expression if a copy could not be
4412/// created.
John McCalldadc5752010-08-24 06:29:42 +00004413static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004414 QualType T,
4415 const InitializedEntity &Entity,
4416 ExprResult CurInit,
4417 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004418 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004419 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004421 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004422 Class = cast<CXXRecordDecl>(Record->getDecl());
4423 if (!Class)
4424 return move(CurInit);
4425
Douglas Gregor5d369002011-01-21 18:05:27 +00004426 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004427 // When certain criteria are met, an implementation is allowed to
4428 // omit the copy/move construction of a class object, even if the
4429 // copy/move constructor and/or destructor for the object have
4430 // side effects. [...]
4431 // - when a temporary class object that has not been bound to a
4432 // reference (12.2) would be copied/moved to a class object
4433 // with the same cv-unqualified type, the copy/move operation
4434 // can be omitted by constructing the temporary object
4435 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004437 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004438 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004440 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004441 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004442 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004443
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004445 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Douglas Gregord5c231e2010-04-24 21:09:25 +00004446 return move(CurInit);
4447
Douglas Gregorf282a762011-01-21 19:38:21 +00004448 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004449 // Only consider constructors and constructor templates. Per
4450 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4451 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004452 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004453 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004455 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4456
Douglas Gregore1314a62009-12-18 05:02:21 +00004457 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004458 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004459 case OR_Success:
4460 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461
Douglas Gregore1314a62009-12-18 05:02:21 +00004462 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004463 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4464 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4465 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004466 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004467 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004468 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004469 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004470 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004471 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
Douglas Gregore1314a62009-12-18 05:02:21 +00004473 case OR_Ambiguous:
4474 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004475 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004476 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004477 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00004478 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479
Douglas Gregore1314a62009-12-18 05:02:21 +00004480 case OR_Deleted:
4481 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004482 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004483 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00004484 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00004485 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004486 }
4487
Douglas Gregor5ab11652010-04-17 22:01:05 +00004488 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004489 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004490 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004491
Anders Carlssona01874b2010-04-21 18:47:17 +00004492 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004493 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004494
4495 if (IsExtraneousCopy) {
4496 // If this is a totally extraneous copy for C++03 reference
4497 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004498 // expression. We don't generate an (elided) copy operation here
4499 // because doing so would require us to pass down a flag to avoid
4500 // infinite recursion, where each step adds another extraneous,
4501 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004502
Douglas Gregor30b52772010-04-18 07:57:34 +00004503 // Instantiate the default arguments of any extra parameters in
4504 // the selected copy constructor, as if we were going to create a
4505 // proper call to the copy constructor.
4506 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4507 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4508 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004509 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00004510 break;
4511
4512 // Build the default argument expression; we don't actually care
4513 // if this succeeds or not, because this routine will complain
4514 // if there was a problem.
4515 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4516 }
4517
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004518 return S.Owned(CurInitExpr);
4519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Eli Friedmanfa0df832012-02-02 03:46:19 +00004521 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004522
Douglas Gregor5ab11652010-04-17 22:01:05 +00004523 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004524 // constructor call (we might have derived-to-base conversions, or
4525 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004526 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004527 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004528 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004529
Douglas Gregord0ace022010-04-25 00:55:24 +00004530 // Actually perform the constructor call.
4531 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004532 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004533 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004534 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004535 CXXConstructExpr::CK_Complete,
4536 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537
Douglas Gregord0ace022010-04-25 00:55:24 +00004538 // If we're supposed to bind temporaries, do so.
4539 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4540 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4541 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004542}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543
Richard Smithc620f552011-10-19 16:55:56 +00004544/// \brief Check whether elidable copy construction for binding a reference to
4545/// a temporary would have succeeded if we were building in C++98 mode, for
4546/// -Wc++98-compat.
4547static void CheckCXX98CompatAccessibleCopy(Sema &S,
4548 const InitializedEntity &Entity,
4549 Expr *CurInitExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004550 assert(S.getLangOpts().CPlusPlus0x);
Richard Smithc620f552011-10-19 16:55:56 +00004551
4552 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4553 if (!Record)
4554 return;
4555
4556 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4557 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4558 == DiagnosticsEngine::Ignored)
4559 return;
4560
4561 // Find constructors which would have been considered.
4562 OverloadCandidateSet CandidateSet(Loc);
4563 LookupCopyAndMoveConstructors(
4564 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4565
4566 // Perform overload resolution.
4567 OverloadCandidateSet::iterator Best;
4568 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4569
4570 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4571 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4572 << CurInitExpr->getSourceRange();
4573
4574 switch (OR) {
4575 case OR_Success:
4576 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00004577 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00004578 // FIXME: Check default arguments as far as that's possible.
4579 break;
4580
4581 case OR_No_Viable_Function:
4582 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004583 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00004584 break;
4585
4586 case OR_Ambiguous:
4587 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004588 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00004589 break;
4590
4591 case OR_Deleted:
4592 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00004593 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00004594 break;
4595 }
4596}
4597
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004598void InitializationSequence::PrintInitLocationNote(Sema &S,
4599 const InitializedEntity &Entity) {
4600 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4601 if (Entity.getDecl()->getLocation().isInvalid())
4602 return;
4603
4604 if (Entity.getDecl()->getDeclName())
4605 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4606 << Entity.getDecl()->getDeclName();
4607 else
4608 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4609 }
4610}
4611
Sebastian Redl112aa822011-07-14 19:07:55 +00004612static bool isReferenceBinding(const InitializationSequence::Step &s) {
4613 return s.Kind == InitializationSequence::SK_BindReference ||
4614 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4615}
4616
Sebastian Redled2e5322011-12-22 14:44:04 +00004617static ExprResult
4618PerformConstructorInitialization(Sema &S,
4619 const InitializedEntity &Entity,
4620 const InitializationKind &Kind,
4621 MultiExprArg Args,
4622 const InitializationSequence::Step& Step,
4623 bool &ConstructorInitRequiresZeroInit) {
4624 unsigned NumArgs = Args.size();
4625 CXXConstructorDecl *Constructor
4626 = cast<CXXConstructorDecl>(Step.Function.Function);
4627 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4628
4629 // Build a call to the selected constructor.
4630 ASTOwningVector<Expr*> ConstructorArgs(S);
4631 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4632 ? Kind.getEqualLoc()
4633 : Kind.getLocation();
4634
4635 if (Kind.getKind() == InitializationKind::IK_Default) {
4636 // Force even a trivial, implicit default constructor to be
4637 // semantically checked. We do this explicitly because we don't build
4638 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00004639 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00004640 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00004641 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00004642 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4643 }
4644
4645 ExprResult CurInit = S.Owned((Expr *)0);
4646
Douglas Gregor6073dca2012-02-24 23:56:31 +00004647 // C++ [over.match.copy]p1:
4648 // - When initializing a temporary to be bound to the first parameter
4649 // of a constructor that takes a reference to possibly cv-qualified
4650 // T as its first argument, called with a single argument in the
4651 // context of direct-initialization, explicit conversion functions
4652 // are also considered.
4653 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4654 Args.size() == 1 &&
4655 Constructor->isCopyOrMoveConstructor();
4656
Sebastian Redled2e5322011-12-22 14:44:04 +00004657 // Determine the arguments required to actually perform the constructor
4658 // call.
4659 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor6073dca2012-02-24 23:56:31 +00004660 Loc, ConstructorArgs,
4661 AllowExplicitConv))
Sebastian Redled2e5322011-12-22 14:44:04 +00004662 return ExprError();
4663
4664
4665 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl04fe1bf2012-03-08 21:05:45 +00004666 (Kind.getKind() == InitializationKind::IK_DirectList ||
4667 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4668 (Kind.getKind() == InitializationKind::IK_Direct ||
4669 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redled2e5322011-12-22 14:44:04 +00004670 // An explicitly-constructed temporary, e.g., X(1, 2).
4671 unsigned NumExprs = ConstructorArgs.size();
4672 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004673 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004674 S.DiagnoseUseOfDecl(Constructor, Loc);
4675
4676 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4677 if (!TSInfo)
4678 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl04fe1bf2012-03-08 21:05:45 +00004679 SourceRange ParenRange;
4680 if (Kind.getKind() != InitializationKind::IK_DirectList)
4681 ParenRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00004682
4683 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4684 Constructor,
4685 TSInfo,
4686 Exprs,
4687 NumExprs,
Sebastian Redl04fe1bf2012-03-08 21:05:45 +00004688 ParenRange,
Sebastian Redled2e5322011-12-22 14:44:04 +00004689 HadMultipleCandidates,
4690 ConstructorInitRequiresZeroInit));
4691 } else {
4692 CXXConstructExpr::ConstructionKind ConstructKind =
4693 CXXConstructExpr::CK_Complete;
4694
4695 if (Entity.getKind() == InitializedEntity::EK_Base) {
4696 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4697 CXXConstructExpr::CK_VirtualBase :
4698 CXXConstructExpr::CK_NonVirtualBase;
4699 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4700 ConstructKind = CXXConstructExpr::CK_Delegating;
4701 }
4702
4703 // Only get the parenthesis range if it is a direct construction.
4704 SourceRange parenRange =
4705 Kind.getKind() == InitializationKind::IK_Direct ?
4706 Kind.getParenRange() : SourceRange();
4707
4708 // If the entity allows NRVO, mark the construction as elidable
4709 // unconditionally.
4710 if (Entity.allowsNRVO())
4711 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4712 Constructor, /*Elidable=*/true,
4713 move_arg(ConstructorArgs),
4714 HadMultipleCandidates,
4715 ConstructorInitRequiresZeroInit,
4716 ConstructKind,
4717 parenRange);
4718 else
4719 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4720 Constructor,
4721 move_arg(ConstructorArgs),
4722 HadMultipleCandidates,
4723 ConstructorInitRequiresZeroInit,
4724 ConstructKind,
4725 parenRange);
4726 }
4727 if (CurInit.isInvalid())
4728 return ExprError();
4729
4730 // Only check access if all of that succeeded.
4731 S.CheckConstructorAccess(Loc, Constructor, Entity,
4732 Step.Function.FoundDecl.getAccess());
4733 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4734
4735 if (shouldBindAsTemporary(Entity))
4736 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4737
4738 return move(CurInit);
4739}
4740
Richard Smitheb3cad52012-06-04 22:27:30 +00004741/// Determine whether the specified InitializedEntity definitely has a lifetime
4742/// longer than the current full-expression. Conservatively returns false if
4743/// it's unclear.
4744static bool
4745InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4746 const InitializedEntity *Top = &Entity;
4747 while (Top->getParent())
4748 Top = Top->getParent();
4749
4750 switch (Top->getKind()) {
4751 case InitializedEntity::EK_Variable:
4752 case InitializedEntity::EK_Result:
4753 case InitializedEntity::EK_Exception:
4754 case InitializedEntity::EK_Member:
4755 case InitializedEntity::EK_New:
4756 case InitializedEntity::EK_Base:
4757 case InitializedEntity::EK_Delegating:
4758 return true;
4759
4760 case InitializedEntity::EK_ArrayElement:
4761 case InitializedEntity::EK_VectorElement:
4762 case InitializedEntity::EK_BlockElement:
4763 case InitializedEntity::EK_ComplexElement:
4764 // Could not determine what the full initialization is. Assume it might not
4765 // outlive the full-expression.
4766 return false;
4767
4768 case InitializedEntity::EK_Parameter:
4769 case InitializedEntity::EK_Temporary:
4770 case InitializedEntity::EK_LambdaCapture:
4771 // The entity being initialized might not outlive the full-expression.
4772 return false;
4773 }
4774
4775 llvm_unreachable("unknown entity kind");
4776}
4777
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004779InitializationSequence::Perform(Sema &S,
4780 const InitializedEntity &Entity,
4781 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004782 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004783 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004784 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004785 unsigned NumArgs = Args.size();
4786 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004787 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004789
Sebastian Redld201edf2011-06-05 13:59:11 +00004790 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004791 // If the declaration is a non-dependent, incomplete array type
4792 // that has an initializer, then its type will be completed once
4793 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004794 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004795 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004796 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004797 if (const IncompleteArrayType *ArrayT
4798 = S.Context.getAsIncompleteArrayType(DeclType)) {
4799 // FIXME: We don't currently have the ability to accurately
4800 // compute the length of an initializer list without
4801 // performing full type-checking of the initializer list
4802 // (since we have to determine where braces are implicitly
4803 // introduced and such). So, we fall back to making the array
4804 // type a dependently-sized array type with no specified
4805 // bound.
4806 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4807 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004808
Douglas Gregor51e77d52009-12-10 17:56:55 +00004809 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004810 if (DeclaratorDecl *DD = Entity.getDecl()) {
4811 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4812 TypeLoc TL = TInfo->getTypeLoc();
4813 if (IncompleteArrayTypeLoc *ArrayLoc
4814 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4815 Brackets = ArrayLoc->getBracketsRange();
4816 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004817 }
4818
4819 *ResultType
4820 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4821 /*NumElts=*/0,
4822 ArrayT->getSizeModifier(),
4823 ArrayT->getIndexTypeCVRQualifiers(),
4824 Brackets);
4825 }
4826
4827 }
4828 }
Sebastian Redla9351792012-02-11 23:51:47 +00004829 if (Kind.getKind() == InitializationKind::IK_Direct &&
4830 !Kind.isExplicitCast()) {
4831 // Rebuild the ParenListExpr.
4832 SourceRange ParenRange = Kind.getParenRange();
4833 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4834 move(Args));
4835 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004836 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00004837 Kind.isExplicitCast() ||
4838 Kind.getKind() == InitializationKind::IK_DirectList);
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004839 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004840 }
4841
Sebastian Redld201edf2011-06-05 13:59:11 +00004842 // No steps means no initialization.
4843 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004844 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Richard Smith2b349ae2012-04-19 06:58:00 +00004846 if (S.getLangOpts().CPlusPlus0x && Entity.getType()->isReferenceType() &&
4847 Args.size() == 1 && isa<InitListExpr>(Args.get()[0]) &&
4848 Entity.getKind() != InitializedEntity::EK_Parameter) {
4849 // Produce a C++98 compatibility warning if we are initializing a reference
4850 // from an initializer list. For parameters, we produce a better warning
4851 // elsewhere.
4852 Expr *Init = Args.get()[0];
4853 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
4854 << Init->getSourceRange();
4855 }
4856
Richard Smitheb3cad52012-06-04 22:27:30 +00004857 // Diagnose cases where we initialize a pointer to an array temporary, and the
4858 // pointer obviously outlives the temporary.
4859 if (Args.size() == 1 && Args.get()[0]->getType()->isArrayType() &&
4860 Entity.getType()->isPointerType() &&
4861 InitializedEntityOutlivesFullExpression(Entity)) {
4862 Expr *Init = Args.get()[0];
4863 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
4864 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
4865 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
4866 << Init->getSourceRange();
4867 }
4868
Douglas Gregor1b303932009-12-22 15:35:07 +00004869 QualType DestType = Entity.getType().getNonReferenceType();
4870 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004871 // the same as Entity.getDecl()->getType() in cases involving type merging,
4872 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004873 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004874 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004875 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004876
John McCalldadc5752010-08-24 06:29:42 +00004877 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004880 // grab the only argument out the Args and place it into the "current"
4881 // initializer.
4882 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004883 case SK_ResolveAddressOfOverloadedFunction:
4884 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004885 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004886 case SK_CastDerivedToBaseLValue:
4887 case SK_BindReference:
4888 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004889 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004890 case SK_UserConversion:
4891 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004892 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004893 case SK_QualificationConversionRValue:
4894 case SK_ConversionSequence:
4895 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004896 case SK_UnwrapInitList:
4897 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004898 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004899 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004900 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004901 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00004902 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00004903 case SK_PassByIndirectCopyRestore:
4904 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004905 case SK_ProduceObjCObject:
4906 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004907 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004908 CurInit = Args.get()[0];
4909 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004910 break;
John McCall34376a62010-12-04 03:47:34 +00004911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004912
Douglas Gregore1314a62009-12-18 05:02:21 +00004913 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00004914 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004915 case SK_ZeroInitialization:
4916 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
4919 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004920 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004921 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004922 for (step_iterator Step = step_begin(), StepEnd = step_end();
4923 Step != StepEnd; ++Step) {
4924 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004925 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926
John Wiegley01296292011-04-08 18:41:53 +00004927 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004929 switch (Step->Kind) {
4930 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004932 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004933 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004934 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004935 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004936 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004937 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004938 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004940 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004941 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004942 case SK_CastDerivedToBaseLValue: {
4943 // We have a derived-to-base cast that produces either an rvalue or an
4944 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945
John McCallcf142162010-08-07 06:22:56 +00004946 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004947
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004948 // Casts to inaccessible base classes are allowed with C-style casts.
4949 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4950 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004951 CurInit.get()->getLocStart(),
4952 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004953 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004954 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregor88d292c2010-05-13 16:44:06 +00004956 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4957 QualType T = SourceType;
4958 if (const PointerType *Pointer = T->getAs<PointerType>())
4959 T = Pointer->getPointeeType();
4960 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004961 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004962 cast<CXXRecordDecl>(RecordTy->getDecl()));
4963 }
4964
John McCall2536c6d2010-08-25 10:28:54 +00004965 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004966 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004967 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004968 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004969 VK_XValue :
4970 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004971 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4972 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004973 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004974 CurInit.get(),
4975 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004976 break;
4977 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004978
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004979 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004980 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004981 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4982 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004983 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004984 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004985 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004986 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004987 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004988 }
Anders Carlssona91be642010-01-29 02:47:33 +00004989
John Wiegley01296292011-04-08 18:41:53 +00004990 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004991 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004992 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4993 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004994 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004995 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004996 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004999 // Reference binding does not have any corresponding ASTs.
5000
5001 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005002 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005003 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005004
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005005 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005006
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005007 case SK_BindReferenceToTemporary:
5008 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005009 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005010 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005011
Douglas Gregorfe314812011-06-21 17:03:29 +00005012 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00005013 CurInit = new (S.Context) MaterializeTemporaryExpr(
5014 Entity.getType().getNonReferenceType(),
5015 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00005016 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00005017
5018 // If we're binding to an Objective-C object that has lifetime, we
5019 // need cleanups.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005020 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor58df5092011-06-22 16:12:01 +00005021 CurInit.get()->getType()->isObjCLifetimeType())
5022 S.ExprNeedsCleanups = true;
5023
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005024 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005026 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005028 /*IsExtraneousCopy=*/true);
5029 break;
5030
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005031 case SK_UserConversion: {
5032 // We have a user-defined conversion that invokes either a constructor
5033 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005034 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005035 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005036 FunctionDecl *Fn = Step->Function.Function;
5037 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005038 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005039 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005040 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005041 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00005042 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00005043 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005044 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005045
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005046 // Determine the arguments required to actually perform the constructor
5047 // call.
John Wiegley01296292011-04-08 18:41:53 +00005048 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005049 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005050 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005051 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005052 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005053
Richard Smithb24f0672012-02-11 19:22:50 +00005054 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00005056 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005057 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00005058 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005059 CXXConstructExpr::CK_Complete,
5060 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005061 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005062 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005063
Anders Carlssona01874b2010-04-21 18:47:17 +00005064 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005065 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00005066 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
John McCalle3027922010-08-25 11:45:40 +00005068 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005069 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5070 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5071 S.IsDerivedFrom(SourceType, Class))
5072 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Douglas Gregor95562572010-04-24 23:45:46 +00005074 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005075 } else {
5076 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005077 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00005078 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00005079 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00005080 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
5082 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005083 // derived-to-base conversion? I believe the answer is "no", because
5084 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005085 ExprResult CurInitExprRes =
5086 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5087 FoundFn, Conversion);
5088 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005089 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005090 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005091
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005092 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005093 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5094 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005095 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005096 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
John McCalle3027922010-08-25 11:45:40 +00005098 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005099
Douglas Gregor95562572010-04-24 23:45:46 +00005100 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102
Sebastian Redl112aa822011-07-14 19:07:55 +00005103 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005104 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5105
5106 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005107 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005108 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005110 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005111 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005112 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005113 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00005114 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005115 }
5116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
John McCallcf142162010-08-07 06:22:56 +00005118 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005119 CurInit.get()->getType(),
5120 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005121 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005122 if (MaybeBindToTemp)
5123 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005124 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005125 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5126 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005127 break;
5128 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005129
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005130 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005131 case SK_QualificationConversionXValue:
5132 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005133 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005134 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005135 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005136 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005137 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005138 VK_XValue :
5139 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005140 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005141 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005142 }
5143
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005144 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005145 Sema::CheckedConversionKind CCK
5146 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5147 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005148 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005149 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005150 ExprResult CurInitExprRes =
5151 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005152 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005153 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005154 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005155 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005156 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Douglas Gregor51e77d52009-12-10 17:56:55 +00005159 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005160 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005161 // Hack: We must pass *ResultType if available in order to set the type
5162 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5163 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5164 // temporary, not a reference, so we should pass Ty.
5165 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5166 // Since this step is never used for a reference directly, we explicitly
5167 // unwrap references here and rewrap them afterwards.
5168 // We also need to create a InitializeTemporary entity for this.
5169 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redle0691ea2012-03-07 16:10:45 +00005170 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl29526f02011-11-27 16:50:07 +00005171 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5172 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5173 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl5a41f682012-02-12 16:37:24 +00005174 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00005175 !S.getLangOpts().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005176 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005177 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005178
Sebastian Redl29526f02011-11-27 16:50:07 +00005179 if (ResultType) {
5180 if ((*ResultType)->isRValueReferenceType())
5181 Ty = S.Context.getRValueReferenceType(Ty);
5182 else if ((*ResultType)->isLValueReferenceType())
5183 Ty = S.Context.getLValueReferenceType(Ty,
5184 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5185 *ResultType = Ty;
5186 }
5187
5188 InitListExpr *StructuredInitList =
5189 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005190 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005191 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005192 break;
5193 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005194
Sebastian Redled2e5322011-12-22 14:44:04 +00005195 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00005196 // When an initializer list is passed for a parameter of type "reference
5197 // to object", we don't get an EK_Temporary entity, but instead an
5198 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00005199 // FIXME: This is a hack. What we really should do is create a user
5200 // conversion step for this case, but this makes it considerably more
5201 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00005202 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5203 Entity.getType().getNonReferenceType());
5204 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00005205 assert(Args.size() == 1 && "expected a single argument for list init");
5206 InitListExpr *InitList = cast<InitListExpr>(Args.get()[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00005207 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5208 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005209 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00005210 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5211 Entity,
5212 Kind, move(Arg), *Step,
Sebastian Redled2e5322011-12-22 14:44:04 +00005213 ConstructorInitRequiresZeroInit);
5214 break;
5215 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005216
Sebastian Redl29526f02011-11-27 16:50:07 +00005217 case SK_UnwrapInitList:
5218 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5219 break;
5220
5221 case SK_RewrapInitList: {
5222 Expr *E = CurInit.take();
5223 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5224 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5225 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5226 ILE->setSyntacticForm(Syntactic);
5227 ILE->setType(E->getType());
5228 ILE->setValueKind(E->getValueKind());
5229 CurInit = S.Owned(ILE);
5230 break;
5231 }
5232
Sebastian Redl99f66162012-02-19 12:27:56 +00005233 case SK_ConstructorInitialization: {
5234 // When an initializer list is passed for a parameter of type "reference
5235 // to object", we don't get an EK_Temporary entity, but instead an
5236 // EK_Parameter entity with reference type.
5237 // FIXME: This is a hack. What we really should do is create a user
5238 // conversion step for this case, but this makes it considerably more
5239 // complicated. For now, this will do.
5240 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5241 Entity.getType().getNonReferenceType());
5242 bool UseTemporary = Entity.getType()->isReferenceType();
5243 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5244 : Entity,
5245 Kind, move(Args), *Step,
Sebastian Redled2e5322011-12-22 14:44:04 +00005246 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005247 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00005248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005250 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005251 step_iterator NextStep = Step;
5252 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00005254 (NextStep->Kind == SK_ConstructorInitialization ||
5255 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005256 // The need for zero-initialization is recorded directly into
5257 // the call to the object's constructor within the next step.
5258 ConstructorInitRequiresZeroInit = true;
5259 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005260 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005261 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005262 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5263 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005264 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005265 Kind.getRange().getBegin());
5266
5267 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5268 TSInfo->getType().getNonLValueExprType(S.Context),
5269 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005270 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005271 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005272 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005273 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005274 break;
5275 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005276
5277 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005278 QualType SourceType = CurInit.get()->getType();
5279 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005280 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005281 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5282 if (Result.isInvalid())
5283 return ExprError();
5284 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005285
5286 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005287 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005288 if (ConvTy != Sema::Compatible &&
5289 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005290 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005291 == Sema::Compatible)
5292 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005293 if (CurInitExprRes.isInvalid())
5294 return ExprError();
5295 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005296
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005297 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005298 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5299 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005300 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005301 getAssignmentAction(Entity),
5302 &Complained)) {
5303 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005304 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005305 } else if (Complained)
5306 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005307 break;
5308 }
Eli Friedman78275202009-12-19 08:11:05 +00005309
5310 case SK_StringInit: {
5311 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005312 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005313 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005314 break;
5315 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005316
5317 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005318 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005319 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005320 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005321 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005322
5323 case SK_ArrayInit:
5324 // Okay: we checked everything before creating this step. Note that
5325 // this is a GNU extension.
5326 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005327 << Step->Type << CurInit.get()->getType()
5328 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005329
5330 // If the destination type is an incomplete array type, update the
5331 // type accordingly.
5332 if (ResultType) {
5333 if (const IncompleteArrayType *IncompleteDest
5334 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5335 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005336 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005337 *ResultType = S.Context.getConstantArrayType(
5338 IncompleteDest->getElementType(),
5339 ConstantSource->getSize(),
5340 ArrayType::Normal, 0);
5341 }
5342 }
5343 }
John McCall31168b02011-06-15 23:02:42 +00005344 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005345
Richard Smithebeed412012-02-15 22:38:09 +00005346 case SK_ParenthesizedArrayInit:
5347 // Okay: we checked everything before creating this step. Note that
5348 // this is a GNU extension.
5349 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5350 << CurInit.get()->getSourceRange();
5351 break;
5352
John McCall31168b02011-06-15 23:02:42 +00005353 case SK_PassByIndirectCopyRestore:
5354 case SK_PassByIndirectRestore:
5355 checkIndirectCopyRestoreSource(S, CurInit.get());
5356 CurInit = S.Owned(new (S.Context)
5357 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5358 Step->Kind == SK_PassByIndirectCopyRestore));
5359 break;
5360
5361 case SK_ProduceObjCObject:
5362 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005363 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005364 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005365 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005366
5367 case SK_StdInitializerList: {
5368 QualType Dest = Step->Type;
5369 QualType E;
5370 bool Success = S.isStdInitializerList(Dest, &E);
5371 (void)Success;
5372 assert(Success && "Destination type changed?");
Sebastian Redl249dee52012-03-05 19:35:43 +00005373
5374 // If the element type has a destructor, check it.
5375 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5376 if (!RD->hasIrrelevantDestructor()) {
5377 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5378 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5379 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5380 S.PDiag(diag::err_access_dtor_temp) << E);
5381 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5382 }
5383 }
5384 }
5385
Sebastian Redlc1839b12012-01-17 22:49:42 +00005386 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith2b349ae2012-04-19 06:58:00 +00005387 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5388 << ILE->getSourceRange();
Sebastian Redlc1839b12012-01-17 22:49:42 +00005389 unsigned NumInits = ILE->getNumInits();
5390 SmallVector<Expr*, 16> Converted(NumInits);
5391 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5392 S.Context.getConstantArrayType(E,
5393 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5394 NumInits),
5395 ArrayType::Normal, 0));
5396 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5397 0, HiddenArray);
5398 for (unsigned i = 0; i < NumInits; ++i) {
5399 Element.setElementIndex(i);
5400 ExprResult Init = S.Owned(ILE->getInit(i));
5401 ExprResult Res = S.PerformCopyInitialization(Element,
5402 Init.get()->getExprLoc(),
5403 Init);
5404 assert(!Res.isInvalid() && "Result changed since try phase.");
5405 Converted[i] = Res.take();
5406 }
5407 InitListExpr *Semantic = new (S.Context)
5408 InitListExpr(S.Context, ILE->getLBraceLoc(),
5409 Converted.data(), NumInits, ILE->getRBraceLoc());
5410 Semantic->setSyntacticForm(ILE);
5411 Semantic->setType(Dest);
Sebastian Redlc83ed822012-02-17 08:42:25 +00005412 Semantic->setInitializesStdInitializerList();
Sebastian Redlc1839b12012-01-17 22:49:42 +00005413 CurInit = S.Owned(Semantic);
5414 break;
5415 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005416 }
5417 }
John McCall1f425642010-11-11 03:21:53 +00005418
5419 // Diagnose non-fatal problems with the completed initialization.
5420 if (Entity.getKind() == InitializedEntity::EK_Member &&
5421 cast<FieldDecl>(Entity.getDecl())->isBitField())
5422 S.CheckBitFieldInitialization(Kind.getLocation(),
5423 cast<FieldDecl>(Entity.getDecl()),
5424 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005426 return move(CurInit);
5427}
5428
5429//===----------------------------------------------------------------------===//
5430// Diagnose initialization failures
5431//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005432bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005433 const InitializedEntity &Entity,
5434 const InitializationKind &Kind,
5435 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005436 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005437 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
Douglas Gregor1b303932009-12-22 15:35:07 +00005439 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005440 switch (Failure) {
5441 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005442 // FIXME: Customize for the initialized entity?
5443 if (NumArgs == 0)
5444 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5445 << DestType.getNonReferenceType();
5446 else // FIXME: diagnostic below could be better!
5447 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5448 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005449 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005450
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005451 case FK_ArrayNeedsInitList:
5452 case FK_ArrayNeedsInitListOrStringLiteral:
5453 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5454 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5455 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456
Douglas Gregore2f943b2011-02-22 18:29:51 +00005457 case FK_ArrayTypeMismatch:
5458 case FK_NonConstantArrayInit:
5459 S.Diag(Kind.getLocation(),
5460 (Failure == FK_ArrayTypeMismatch
5461 ? diag::err_array_init_different_type
5462 : diag::err_array_init_non_constant_array))
5463 << DestType.getNonReferenceType()
5464 << Args[0]->getType()
5465 << Args[0]->getSourceRange();
5466 break;
5467
John McCalla59dc2f2012-01-05 00:13:19 +00005468 case FK_VariableLengthArrayHasInitializer:
5469 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5470 << Args[0]->getSourceRange();
5471 break;
5472
John McCall16df1e52010-03-30 21:47:33 +00005473 case FK_AddressOfOverloadFailed: {
5474 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005476 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005477 true,
5478 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005479 break;
John McCall16df1e52010-03-30 21:47:33 +00005480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005482 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005483 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005484 switch (FailedOverloadResult) {
5485 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005486 if (Failure == FK_UserConversionOverloadFailed)
5487 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5488 << Args[0]->getType() << DestType
5489 << Args[0]->getSourceRange();
5490 else
5491 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5492 << DestType << Args[0]->getType()
5493 << Args[0]->getSourceRange();
5494
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005495 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5496 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005497 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005499 case OR_No_Viable_Function:
5500 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5501 << Args[0]->getType() << DestType.getNonReferenceType()
5502 << Args[0]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005503 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5504 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005505 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005506
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005507 case OR_Deleted: {
5508 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5509 << Args[0]->getType() << DestType.getNonReferenceType()
5510 << Args[0]->getSourceRange();
5511 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005512 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005513 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5514 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005515 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00005516 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005517 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005518 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005519 }
5520 break;
5521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005523 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005524 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005525 }
5526 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005528 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005529 if (isa<InitListExpr>(Args[0])) {
5530 S.Diag(Kind.getLocation(),
5531 diag::err_lvalue_reference_bind_to_initlist)
5532 << DestType.getNonReferenceType().isVolatileQualified()
5533 << DestType.getNonReferenceType()
5534 << Args[0]->getSourceRange();
5535 break;
5536 }
5537 // Intentional fallthrough
5538
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005539 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005541 Failure == FK_NonConstLValueReferenceBindingToTemporary
5542 ? diag::err_lvalue_reference_bind_to_temporary
5543 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005544 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005545 << DestType.getNonReferenceType()
5546 << Args[0]->getType()
5547 << Args[0]->getSourceRange();
5548 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005550 case FK_RValueReferenceBindingToLValue:
5551 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005552 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005553 << Args[0]->getSourceRange();
5554 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005556 case FK_ReferenceInitDropsQualifiers:
5557 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5558 << DestType.getNonReferenceType()
5559 << Args[0]->getType()
5560 << Args[0]->getSourceRange();
5561 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005563 case FK_ReferenceInitFailed:
5564 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5565 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005566 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005567 << Args[0]->getType()
5568 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005569 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5570 Args[0]->getType()->isObjCObjectPointerType())
5571 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005572 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573
Douglas Gregorb491ed32011-02-19 21:32:49 +00005574 case FK_ConversionFailed: {
5575 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005576 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005577 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005578 << DestType
John McCall086a4642010-11-24 05:12:34 +00005579 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005580 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005581 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005582 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5583 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005584 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5585 Args[0]->getType()->isObjCObjectPointerType())
5586 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005587 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005588 }
John Wiegley01296292011-04-08 18:41:53 +00005589
5590 case FK_ConversionFromPropertyFailed:
5591 // No-op. This error has already been reported.
5592 break;
5593
Douglas Gregor51e77d52009-12-10 17:56:55 +00005594 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005595 SourceRange R;
5596
5597 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005598 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005599 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005601 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005602
Douglas Gregor8ec51732010-09-08 21:40:08 +00005603 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5604 if (Kind.isCStyleOrFunctionalCast())
5605 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5606 << R;
5607 else
5608 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5609 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005610 break;
5611 }
5612
5613 case FK_ReferenceBindingToInitList:
5614 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5615 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5616 break;
5617
5618 case FK_InitListBadDestinationType:
5619 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5620 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005622
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005623 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005624 case FK_ConstructorOverloadFailed: {
5625 SourceRange ArgsRange;
5626 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005628 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005630 if (Failure == FK_ListConstructorOverloadFailed) {
5631 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5632 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5633 Args = InitList->getInits();
5634 NumArgs = InitList->getNumInits();
5635 }
5636
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005637 // FIXME: Using "DestType" for the entity we're printing is probably
5638 // bad.
5639 switch (FailedOverloadResult) {
5640 case OR_Ambiguous:
5641 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5642 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005643 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005644 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005647 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005648 if (Kind.getKind() == InitializationKind::IK_Default &&
5649 (Entity.getKind() == InitializedEntity::EK_Base ||
5650 Entity.getKind() == InitializedEntity::EK_Member) &&
5651 isa<CXXConstructorDecl>(S.CurContext)) {
5652 // This is implicit default initialization of a member or
5653 // base within a constructor. If no viable function was
5654 // found, notify the user that she needs to explicitly
5655 // initialize this base/member.
5656 CXXConstructorDecl *Constructor
5657 = cast<CXXConstructorDecl>(S.CurContext);
5658 if (Entity.getKind() == InitializedEntity::EK_Base) {
5659 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5660 << Constructor->isImplicit()
5661 << S.Context.getTypeDeclType(Constructor->getParent())
5662 << /*base=*/0
5663 << Entity.getType();
5664
5665 RecordDecl *BaseDecl
5666 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5667 ->getDecl();
5668 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5669 << S.Context.getTagDeclType(BaseDecl);
5670 } else {
5671 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5672 << Constructor->isImplicit()
5673 << S.Context.getTypeDeclType(Constructor->getParent())
5674 << /*member=*/1
5675 << Entity.getName();
5676 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5677
5678 if (const RecordType *Record
5679 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005681 diag::note_previous_decl)
5682 << S.Context.getTagDeclType(Record->getDecl());
5683 }
5684 break;
5685 }
5686
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005687 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5688 << DestType << ArgsRange;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005689 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5690 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005691 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005692
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005693 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005694 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005695 OverloadingResult Ovl
5696 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00005697 if (Ovl != OR_Deleted) {
5698 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5699 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005700 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00005701 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005702 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00005703
5704 // If this is a defaulted or implicitly-declared function, then
5705 // it was implicitly deleted. Make it clear that the deletion was
5706 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00005707 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00005708 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00005709 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00005710 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00005711 else
5712 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5713 << true << DestType << ArgsRange;
5714
5715 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005716 break;
5717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005718
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005719 case OR_Success:
5720 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005721 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005722 }
David Blaikie60deeee2012-01-17 08:24:58 +00005723 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Douglas Gregor85dabae2009-12-16 01:38:02 +00005725 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005726 if (Entity.getKind() == InitializedEntity::EK_Member &&
5727 isa<CXXConstructorDecl>(S.CurContext)) {
5728 // This is implicit default-initialization of a const member in
5729 // a constructor. Complain that it needs to be explicitly
5730 // initialized.
5731 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5732 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5733 << Constructor->isImplicit()
5734 << S.Context.getTypeDeclType(Constructor->getParent())
5735 << /*const=*/1
5736 << Entity.getName();
5737 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5738 << Entity.getName();
5739 } else {
5740 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5741 << DestType << (bool)DestType->getAs<RecordType>();
5742 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005745 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00005746 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005747 diag::err_init_incomplete_type);
5748 break;
5749
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005750 case FK_ListInitializationFailed: {
5751 // Run the init list checker again to emit diagnostics.
5752 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5753 QualType DestType = Entity.getType();
5754 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005755 DestType, /*VerifyOnly=*/false,
Sebastian Redl5a41f682012-02-12 16:37:24 +00005756 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00005757 !S.getLangOpts().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005758 assert(DiagnoseInitList.HadError() &&
5759 "Inconsistent init list check result.");
5760 break;
5761 }
John McCall4124c492011-10-17 18:40:02 +00005762
5763 case FK_PlaceholderType: {
5764 // FIXME: Already diagnosed!
5765 break;
5766 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005767
5768 case FK_InitListElementCopyFailure: {
5769 // Try to perform all copies again.
5770 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5771 unsigned NumInits = InitList->getNumInits();
5772 QualType DestType = Entity.getType();
5773 QualType E;
5774 bool Success = S.isStdInitializerList(DestType, &E);
5775 (void)Success;
5776 assert(Success && "Where did the std::initializer_list go?");
5777 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5778 S.Context.getConstantArrayType(E,
5779 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5780 NumInits),
5781 ArrayType::Normal, 0));
5782 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5783 0, HiddenArray);
5784 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5785 // where the init list type is wrong, e.g.
5786 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5787 // FIXME: Emit a note if we hit the limit?
5788 int ErrorCount = 0;
5789 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5790 Element.setElementIndex(i);
5791 ExprResult Init = S.Owned(InitList->getInit(i));
5792 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5793 .isInvalid())
5794 ++ErrorCount;
5795 }
5796 break;
5797 }
Sebastian Redl048a6d72012-04-01 19:54:59 +00005798
5799 case FK_ExplicitConstructor: {
5800 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
5801 << Args[0]->getSourceRange();
5802 OverloadCandidateSet::iterator Best;
5803 OverloadingResult Ovl
5804 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00005805 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00005806 assert(Ovl == OR_Success && "Inconsistent overload resolution");
5807 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5808 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
5809 break;
5810 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005812
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005813 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005814 return true;
5815}
Douglas Gregore1314a62009-12-18 05:02:21 +00005816
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005817void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005818 switch (SequenceKind) {
5819 case FailedSequence: {
5820 OS << "Failed sequence: ";
5821 switch (Failure) {
5822 case FK_TooManyInitsForReference:
5823 OS << "too many initializers for reference";
5824 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005825
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005826 case FK_ArrayNeedsInitList:
5827 OS << "array requires initializer list";
5828 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005830 case FK_ArrayNeedsInitListOrStringLiteral:
5831 OS << "array requires initializer list or string literal";
5832 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833
Douglas Gregore2f943b2011-02-22 18:29:51 +00005834 case FK_ArrayTypeMismatch:
5835 OS << "array type mismatch";
5836 break;
5837
5838 case FK_NonConstantArrayInit:
5839 OS << "non-constant array initializer";
5840 break;
5841
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005842 case FK_AddressOfOverloadFailed:
5843 OS << "address of overloaded function failed";
5844 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005845
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005846 case FK_ReferenceInitOverloadFailed:
5847 OS << "overload resolution for reference initialization failed";
5848 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005849
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005850 case FK_NonConstLValueReferenceBindingToTemporary:
5851 OS << "non-const lvalue reference bound to temporary";
5852 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005854 case FK_NonConstLValueReferenceBindingToUnrelated:
5855 OS << "non-const lvalue reference bound to unrelated type";
5856 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005857
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005858 case FK_RValueReferenceBindingToLValue:
5859 OS << "rvalue reference bound to an lvalue";
5860 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005861
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005862 case FK_ReferenceInitDropsQualifiers:
5863 OS << "reference initialization drops qualifiers";
5864 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005866 case FK_ReferenceInitFailed:
5867 OS << "reference initialization failed";
5868 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005869
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005870 case FK_ConversionFailed:
5871 OS << "conversion failed";
5872 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
John Wiegley01296292011-04-08 18:41:53 +00005874 case FK_ConversionFromPropertyFailed:
5875 OS << "conversion from property failed";
5876 break;
5877
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005878 case FK_TooManyInitsForScalar:
5879 OS << "too many initializers for scalar";
5880 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005881
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005882 case FK_ReferenceBindingToInitList:
5883 OS << "referencing binding to initializer list";
5884 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005885
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005886 case FK_InitListBadDestinationType:
5887 OS << "initializer list for non-aggregate, non-scalar type";
5888 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005889
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005890 case FK_UserConversionOverloadFailed:
5891 OS << "overloading failed for user-defined conversion";
5892 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005894 case FK_ConstructorOverloadFailed:
5895 OS << "constructor overloading failed";
5896 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005897
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005898 case FK_DefaultInitOfConst:
5899 OS << "default initialization of a const variable";
5900 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005901
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005902 case FK_Incomplete:
5903 OS << "initialization of incomplete type";
5904 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005905
5906 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005907 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005908 break;
5909
John McCalla59dc2f2012-01-05 00:13:19 +00005910 case FK_VariableLengthArrayHasInitializer:
5911 OS << "variable length array has an initializer";
5912 break;
5913
John McCall4124c492011-10-17 18:40:02 +00005914 case FK_PlaceholderType:
5915 OS << "initializer expression isn't contextually valid";
5916 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005917
5918 case FK_ListConstructorOverloadFailed:
5919 OS << "list constructor overloading failed";
5920 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005921
5922 case FK_InitListElementCopyFailure:
5923 OS << "copy construction of initializer list element failed";
5924 break;
Sebastian Redl048a6d72012-04-01 19:54:59 +00005925
5926 case FK_ExplicitConstructor:
5927 OS << "list copy initialization chose explicit constructor";
5928 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005930 OS << '\n';
5931 return;
5932 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005934 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005935 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005936 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
Sebastian Redld201edf2011-06-05 13:59:11 +00005938 case NormalSequence:
5939 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005940 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005942
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005943 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5944 if (S != step_begin()) {
5945 OS << " -> ";
5946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005947
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005948 switch (S->Kind) {
5949 case SK_ResolveAddressOfOverloadedFunction:
5950 OS << "resolve address of overloaded function";
5951 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005952
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005953 case SK_CastDerivedToBaseRValue:
5954 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5955 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005956
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005957 case SK_CastDerivedToBaseXValue:
5958 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5959 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005960
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005961 case SK_CastDerivedToBaseLValue:
5962 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5963 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005964
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005965 case SK_BindReference:
5966 OS << "bind reference to lvalue";
5967 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005968
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005969 case SK_BindReferenceToTemporary:
5970 OS << "bind reference to a temporary";
5971 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005973 case SK_ExtraneousCopyToTemporary:
5974 OS << "extraneous C++03 copy to temporary";
5975 break;
5976
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005977 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005978 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005979 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005980
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005981 case SK_QualificationConversionRValue:
5982 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005983 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005984
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005985 case SK_QualificationConversionXValue:
5986 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005987 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005988
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005989 case SK_QualificationConversionLValue:
5990 OS << "qualification conversion (lvalue)";
5991 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005992
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005993 case SK_ConversionSequence:
5994 OS << "implicit conversion sequence (";
5995 S->ICS->DebugPrint(); // FIXME: use OS
5996 OS << ")";
5997 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005998
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005999 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006000 OS << "list aggregate initialization";
6001 break;
6002
6003 case SK_ListConstructorCall:
6004 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006005 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006
Sebastian Redl29526f02011-11-27 16:50:07 +00006007 case SK_UnwrapInitList:
6008 OS << "unwrap reference initializer list";
6009 break;
6010
6011 case SK_RewrapInitList:
6012 OS << "rewrap reference initializer list";
6013 break;
6014
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006015 case SK_ConstructorInitialization:
6016 OS << "constructor initialization";
6017 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006019 case SK_ZeroInitialization:
6020 OS << "zero initialization";
6021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006022
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006023 case SK_CAssignment:
6024 OS << "C assignment";
6025 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006026
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006027 case SK_StringInit:
6028 OS << "string initialization";
6029 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006030
6031 case SK_ObjCObjectConversion:
6032 OS << "Objective-C object conversion";
6033 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006034
6035 case SK_ArrayInit:
6036 OS << "array initialization";
6037 break;
John McCall31168b02011-06-15 23:02:42 +00006038
Richard Smithebeed412012-02-15 22:38:09 +00006039 case SK_ParenthesizedArrayInit:
6040 OS << "parenthesized array initialization";
6041 break;
6042
John McCall31168b02011-06-15 23:02:42 +00006043 case SK_PassByIndirectCopyRestore:
6044 OS << "pass by indirect copy and restore";
6045 break;
6046
6047 case SK_PassByIndirectRestore:
6048 OS << "pass by indirect restore";
6049 break;
6050
6051 case SK_ProduceObjCObject:
6052 OS << "Objective-C object retension";
6053 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006054
6055 case SK_StdInitializerList:
6056 OS << "std::initializer_list from initializer list";
6057 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006058 }
6059 }
6060}
6061
6062void InitializationSequence::dump() const {
6063 dump(llvm::errs());
6064}
6065
Richard Smith66e05fe2012-01-18 05:21:49 +00006066static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6067 QualType EntityType,
6068 const Expr *PreInit,
6069 const Expr *PostInit) {
6070 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6071 return;
6072
6073 // A narrowing conversion can only appear as the final implicit conversion in
6074 // an initialization sequence.
6075 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6076 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6077 return;
6078
6079 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6080 const StandardConversionSequence *SCS = 0;
6081 switch (ICS.getKind()) {
6082 case ImplicitConversionSequence::StandardConversion:
6083 SCS = &ICS.Standard;
6084 break;
6085 case ImplicitConversionSequence::UserDefinedConversion:
6086 SCS = &ICS.UserDefined.After;
6087 break;
6088 case ImplicitConversionSequence::AmbiguousConversion:
6089 case ImplicitConversionSequence::EllipsisConversion:
6090 case ImplicitConversionSequence::BadConversion:
6091 return;
6092 }
6093
6094 // Determine the type prior to the narrowing conversion. If a conversion
6095 // operator was used, this may be different from both the type of the entity
6096 // and of the pre-initialization expression.
6097 QualType PreNarrowingType = PreInit->getType();
6098 if (Seq.step_begin() + 1 != Seq.step_end())
6099 PreNarrowingType = Seq.step_end()[-2].Type;
6100
6101 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6102 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00006103 QualType ConstantType;
6104 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6105 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00006106 case NK_Not_Narrowing:
6107 // No narrowing occurred.
6108 return;
6109
6110 case NK_Type_Narrowing:
6111 // This was a floating-to-integer conversion, which is always considered a
6112 // narrowing conversion even if the value is a constant and can be
6113 // represented exactly as an integer.
6114 S.Diag(PostInit->getLocStart(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00006115 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregor84585ab2012-01-23 15:29:33 +00006116 diag::warn_init_list_type_narrowing
6117 : S.isSFINAEContext()?
6118 diag::err_init_list_type_narrowing_sfinae
6119 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006120 << PostInit->getSourceRange()
6121 << PreNarrowingType.getLocalUnqualifiedType()
6122 << EntityType.getLocalUnqualifiedType();
6123 break;
6124
6125 case NK_Constant_Narrowing:
6126 // A constant value was narrowed.
6127 S.Diag(PostInit->getLocStart(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00006128 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregor84585ab2012-01-23 15:29:33 +00006129 diag::warn_init_list_constant_narrowing
6130 : S.isSFINAEContext()?
6131 diag::err_init_list_constant_narrowing_sfinae
6132 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006133 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00006134 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00006135 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00006136 break;
6137
6138 case NK_Variable_Narrowing:
6139 // A variable's value may have been narrowed.
6140 S.Diag(PostInit->getLocStart(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00006141 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregor84585ab2012-01-23 15:29:33 +00006142 diag::warn_init_list_variable_narrowing
6143 : S.isSFINAEContext()?
6144 diag::err_init_list_variable_narrowing_sfinae
6145 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006146 << PostInit->getSourceRange()
6147 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00006148 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00006149 break;
6150 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006151
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006152 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006153 llvm::raw_svector_ostream OS(StaticCast);
6154 OS << "static_cast<";
6155 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6156 // It's important to use the typedef's name if there is one so that the
6157 // fixit doesn't break code using types like int64_t.
6158 //
6159 // FIXME: This will break if the typedef requires qualification. But
6160 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006161 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006162 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00006163 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006164 else {
6165 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6166 // with a broken cast.
6167 return;
6168 }
6169 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00006170 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6171 << PostInit->getSourceRange()
6172 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006173 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00006174 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006175}
6176
Douglas Gregore1314a62009-12-18 05:02:21 +00006177//===----------------------------------------------------------------------===//
6178// Initialization helper functions
6179//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00006180bool
6181Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6182 ExprResult Init) {
6183 if (Init.isInvalid())
6184 return false;
6185
6186 Expr *InitE = Init.get();
6187 assert(InitE && "No initialization expression");
6188
6189 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
6190 SourceLocation());
6191 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00006192 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00006193}
6194
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006195ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00006196Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6197 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006198 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006199 bool TopLevelOfInitList,
6200 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006201 if (Init.isInvalid())
6202 return ExprError();
6203
John McCall1f425642010-11-11 03:21:53 +00006204 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00006205 assert(InitE && "No initialization expression?");
6206
6207 if (EqualLoc.isInvalid())
6208 EqualLoc = InitE->getLocStart();
6209
6210 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00006211 EqualLoc,
6212 AllowExplicit);
Douglas Gregore1314a62009-12-18 05:02:21 +00006213 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6214 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00006215
Richard Smith66e05fe2012-01-18 05:21:49 +00006216 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6217
6218 if (!Result.isInvalid() && TopLevelOfInitList)
6219 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6220 InitE, Result.get());
6221
6222 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00006223}