blob: f4f2663bc8bc65e7a4e236280a32f445586159ce [file] [log] [blame]
Steve Naroff0cca7492008-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 Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCallce6c9b72011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000051
52 switch (SL->getKind()) {
53 case StringLiteral::Ascii:
54 case StringLiteral::UTF8:
55 // char array can be initialized with a narrow string.
56 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000058 case StringLiteral::UTF16:
59 return ElemTy->isChar16Type() ? Init : 0;
60 case StringLiteral::UTF32:
61 return ElemTy->isChar32Type() ? Init : 0;
62 case StringLiteral::Wide:
63 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
64 // correction from DR343): "An array with element type compatible with a
65 // qualified or unqualified version of wchar_t may be initialized by a wide
66 // string literal, optionally enclosed in braces."
67 if (Context.typesAreCompatible(Context.getWCharType(),
68 ElemTy.getUnqualifiedType()))
69 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000070
Douglas Gregor5cee1192011-07-27 05:40:30 +000071 return 0;
72 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Douglas Gregor5cee1192011-07-27 05:40:30 +000074 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000075}
76
John McCallce6c9b72011-02-21 07:22:22 +000077static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
78 const ArrayType *arrayType = Context.getAsArrayType(declType);
79 if (!arrayType) return 0;
80
81 return IsStringInit(init, arrayType, Context);
82}
83
John McCallfef8b342011-02-21 07:57:55 +000084static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
85 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000086 // Get the length of the string as parsed.
87 uint64_t StrLength =
88 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
89
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattnerdd8e0062009-02-24 22:27:37 +000091 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000092 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000093 // being initialized to a string literal.
94 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000095 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000100 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Eli Friedman8718a6a2009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000105 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000108 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
112 //
113 // unsigned char a[2] = "\pa";
114 if (SL->isPascal())
115 StrLength--;
116 }
117
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
120 S.Diag(Str->getSourceRange().getBegin(),
121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
123 } else {
124 // C99 6.7.8p14.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
129 }
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Eli Friedman8718a6a2009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000136}
137
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregor9e80f722009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000156/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000169namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000173 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000174 bool AllowBraceElision;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000175 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
176 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000178 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000179 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000181 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
201 unsigned &Index,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000205 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000211 unsigned &Index,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000214 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000215 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000218 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000219 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000226 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000227 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000232 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000233 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000234 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
237 unsigned &Index,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000240 bool FinishSubobjectInit,
241 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000249 Expr *expr);
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000261 void CheckValueInitializable(const InitializedEntity &Entity);
262
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000263public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000264 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000267 bool HadError() { return hadError; }
268
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272};
Chris Lattner8b419b92009-02-24 22:48:58 +0000273} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000274
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000275void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276 assert(VerifyOnly &&
277 "CheckValueInitializable is only inteded for verification mode.");
278
279 SourceLocation Loc;
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
284 hadError = true;
285}
286
Douglas Gregord6d37de2009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 bool &RequiresSecondPass) {
291 SourceLocation Loc = ILE->getSourceRange().getBegin();
292 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
296 // FIXME: We probably don't need to handle references
297 // specially here, since value-initialization of references is
298 // handled in InitializationSequence.
299 if (Field->getType()->isReferenceType()) {
300 // C++ [dcl.init.aggr]p9:
301 // If an incomplete or empty initializer-list leaves a
302 // member of reference type uninitialized, the program is
303 // ill-formed.
304 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
305 << Field->getType()
306 << ILE->getSyntacticForm()->getSourceRange();
307 SemaRef.Diag(Field->getLocation(),
308 diag::note_uninit_reference_member);
309 hadError = true;
310 return;
311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000312
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
314 true);
315 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
316 if (!InitSeq) {
317 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
318 hadError = true;
319 return;
320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321
John McCall60d7b3a2010-08-24 06:29:42 +0000322 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000323 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000324 if (MemberInit.isInvalid()) {
325 hadError = true;
326 return;
327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 if (hadError) {
330 // Do nothing
331 } else if (Init < NumInits) {
332 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000333 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000334 // Value-initialization requires a constructor call, so
335 // extend the initializer list to include the constructor
336 // call and make a note that we'll need to take another pass
337 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000338 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000339 RequiresSecondPass = true;
340 }
341 } else if (InitListExpr *InnerILE
342 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343 FillInValueInitializations(MemberEntity, InnerILE,
344 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345}
346
Douglas Gregor4c678342009-01-28 21:54:33 +0000347/// Recursively replaces NULL values within the given initializer list
348/// with expressions that perform value-initialization of the
349/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
352 InitListExpr *ILE,
353 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000355 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 SourceLocation Loc = ILE->getSourceRange().getBegin();
357 if (ILE->getSyntacticForm())
358 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Ted Kremenek6217b802009-07-29 21:53:49 +0000360 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361 if (RType->getDecl()->isUnion() &&
362 ILE->getInitializedFieldInUnion())
363 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
364 Entity, ILE, RequiresSecondPass);
365 else {
366 unsigned Init = 0;
367 for (RecordDecl::field_iterator
368 Field = RType->getDecl()->field_begin(),
369 FieldEnd = RType->getDecl()->field_end();
370 Field != FieldEnd; ++Field) {
371 if (Field->isUnnamedBitfield())
372 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000373
Douglas Gregord6d37de2009-12-22 00:05:34 +0000374 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000375 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000376
377 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
378 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380
Douglas Gregord6d37de2009-12-22 00:05:34 +0000381 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000382
Douglas Gregord6d37de2009-12-22 00:05:34 +0000383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
386 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 }
388
389 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000391
392 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000394 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 unsigned NumInits = ILE->getNumInits();
396 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000397 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000398 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
400 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000402 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000403 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000404 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000408 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000409 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000410
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000411
Douglas Gregor87fd7032009-02-02 17:43:21 +0000412 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000413 if (hadError)
414 return;
415
Anders Carlssond3d824d2010-01-23 04:34:47 +0000416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
417 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 ElementEntity.setElementIndex(Init);
419
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000420 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
421 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000422 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
423 true);
424 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
425 if (!InitSeq) {
426 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000427 hadError = true;
428 return;
429 }
430
John McCall60d7b3a2010-08-24 06:29:42 +0000431 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000432 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000433 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000434 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000435 return;
436 }
437
438 if (hadError) {
439 // Do nothing
440 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000441 // For arrays, just set the expression used for value-initialization
442 // of the "holes" in the array.
443 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
444 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
445 else
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000447 } else {
448 // For arrays, just set the expression used for value-initialization
449 // of the rest of elements and exit.
450 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
451 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
452 return;
453 }
454
Sebastian Redl7491c492011-06-05 13:59:11 +0000455 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000456 // Value-initialization requires a constructor call, so
457 // extend the initializer list to include the constructor
458 // call and make a note that we'll need to take another pass
459 // through the initializer list.
460 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
461 RequiresSecondPass = true;
462 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000463 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000464 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000465 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000466 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000467 }
468}
469
Chris Lattner68355a52009-01-29 05:10:57 +0000470
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000472 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000473 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000474 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000475 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000476
Eli Friedmanb85f7072008-05-19 19:16:24 +0000477 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000479 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000481 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000482 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000483 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000484
Sebastian Redl14b0c192011-09-24 17:48:00 +0000485 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000486 bool RequiresSecondPass = false;
487 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000488 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490 RequiresSecondPass);
491 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000492}
493
494int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000495 // FIXME: use a proper constant
496 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000497 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000498 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
500 }
501 return maxElements;
502}
503
504int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000508 Field = structDecl->field_begin(),
509 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000511 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000512 ++InitializableMembers;
513 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000514 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000515 return std::min(InitializableMembers, 1);
516 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000517}
518
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000519void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000520 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 QualType T, unsigned &Index,
522 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000523 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000524 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Steve Naroff0cca7492008-05-01 22:18:59 +0000526 if (T->isArrayType())
527 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000528 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000529 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000530 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000531 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000532 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000533 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000534
Eli Friedman402256f2008-05-25 13:49:22 +0000535 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000536 if (!VerifyOnly)
537 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
538 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000539 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000540 hadError = true;
541 return;
542 }
543
Douglas Gregor4c678342009-01-28 21:54:33 +0000544 // Build a structured initializer list corresponding to this subobject.
545 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000546 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
547 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000548 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
549 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000550 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000551
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000553 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000555 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000556 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000557 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000558
559 if (VerifyOnly) {
560 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
561 hadError = true;
562 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000563 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000564
Sebastian Redlc2235182011-10-16 18:19:28 +0000565 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000566 // Update the structured sub-object initializer so that it's ending
567 // range corresponds with the end of the last initializer it used.
568 if (EndIndex < ParentIList->getNumInits()) {
569 SourceLocation EndLoc
570 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
571 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573
Sebastian Redlc2235182011-10-16 18:19:28 +0000574 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000575 if (T->isArrayType() || T->isRecordType()) {
576 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000577 AllowBraceElision ? diag::warn_missing_braces :
578 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000579 << StructuredSubobjectInitList->getSourceRange()
580 << FixItHint::CreateInsertion(
581 StructuredSubobjectInitList->getLocStart(), "{")
582 << FixItHint::CreateInsertion(
583 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000585 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000586 if (!AllowBraceElision)
587 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000588 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000589 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000590}
591
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000592void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000593 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 unsigned &Index,
595 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000599 if (!VerifyOnly) {
600 SyntacticToSemantic[IList] = StructuredList;
601 StructuredList->setSyntacticForm(IList);
602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000604 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000605 if (!VerifyOnly) {
606 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
607 IList->setType(ExprTy);
608 StructuredList->setType(ExprTy);
609 }
Eli Friedman638e1442008-05-25 13:22:35 +0000610 if (hadError)
611 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000612
Eli Friedman638e1442008-05-25 13:22:35 +0000613 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000614 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000615 if (VerifyOnly) {
616 if (SemaRef.getLangOptions().CPlusPlus ||
617 (SemaRef.getLangOptions().OpenCL &&
618 IList->getType()->isVectorType())) {
619 hadError = true;
620 }
621 return;
622 }
623
Eli Friedmane5408582009-05-29 20:20:05 +0000624 if (StructuredIndex == 1 &&
625 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000626 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000627 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000628 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000629 hadError = true;
630 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000631 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000632 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000633 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000634 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000635 // Don't complain for incomplete types, since we'll get an error
636 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000637 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000638 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 CurrentObjectType->isArrayType()? 0 :
640 CurrentObjectType->isVectorType()? 1 :
641 CurrentObjectType->isScalarType()? 2 :
642 CurrentObjectType->isUnionType()? 3 :
643 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000644
645 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000646 if (SemaRef.getLangOptions().CPlusPlus) {
647 DK = diag::err_excess_initializers;
648 hadError = true;
649 }
Nate Begeman08634522009-07-07 21:53:06 +0000650 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
651 DK = diag::err_excess_initializers;
652 hadError = true;
653 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000654
Chris Lattner08202542009-02-24 22:50:46 +0000655 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000656 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000657 }
658 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000659
Sebastian Redl14b0c192011-09-24 17:48:00 +0000660 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
661 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000662 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000663 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000664 << FixItHint::CreateRemoval(IList->getLocStart())
665 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000666}
667
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000668void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000669 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000670 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000671 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 unsigned &Index,
673 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000674 unsigned &StructuredIndex,
675 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000676 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
677 // Explicitly braced initializer for complex type can be real+imaginary
678 // parts.
679 CheckComplexType(Entity, IList, DeclType, Index,
680 StructuredList, StructuredIndex);
681 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000682 CheckScalarType(Entity, IList, DeclType, Index,
683 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000684 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000686 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000687 } else if (DeclType->isAggregateType()) {
688 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000689 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000690 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000692 StructuredList, StructuredIndex,
693 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000694 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000695 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000696 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000697 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000698 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000699 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000700 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000701 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000702 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000703 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
704 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000705 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000706 if (!VerifyOnly)
707 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
708 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000709 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000710 } else if (DeclType->isRecordType()) {
711 // C++ [dcl.init]p14:
712 // [...] If the class is an aggregate (8.5.1), and the initializer
713 // is a brace-enclosed list, see 8.5.1.
714 //
715 // Note: 8.5.1 is handled below; here, we diagnose the case where
716 // we have an initializer list and a destination type that is not
717 // an aggregate.
718 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000719 if (!VerifyOnly)
720 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
721 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000722 hadError = true;
723 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000724 CheckReferenceType(Entity, IList, DeclType, Index,
725 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000726 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000727 if (!VerifyOnly)
728 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
729 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000730 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000731 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000732 if (!VerifyOnly)
733 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
734 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000735 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000736 }
737}
738
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000739void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000740 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000741 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000742 unsigned &Index,
743 InitListExpr *StructuredList,
744 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000745 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000746 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
747 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000748 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000749 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000750 = getStructuredSubobjectInit(IList, Index, ElemType,
751 StructuredList, StructuredIndex,
752 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000753 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000754 newStructuredList, newStructuredIndex);
755 ++StructuredIndex;
756 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000757 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000758 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000759 return CheckScalarType(Entity, IList, ElemType, Index,
760 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000761 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000762 return CheckReferenceType(Entity, IList, ElemType, Index,
763 StructuredList, StructuredIndex);
764 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000765
John McCallfef8b342011-02-21 07:57:55 +0000766 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
767 // arrayType can be incomplete if we're initializing a flexible
768 // array member. There's nothing we can do with the completed
769 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000770
John McCallfef8b342011-02-21 07:57:55 +0000771 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000772 if (!VerifyOnly) {
773 CheckStringInit(Str, ElemType, arrayType, SemaRef);
774 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
775 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000776 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000777 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000778 }
John McCallfef8b342011-02-21 07:57:55 +0000779
780 // Fall through for subaggregate initialization.
781
782 } else if (SemaRef.getLangOptions().CPlusPlus) {
783 // C++ [dcl.init.aggr]p12:
784 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000785 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000786 // an initializer-list. If the initializer can initialize a
787 // member, the member is initialized. [...]
788
789 // FIXME: Better EqualLoc?
790 InitializationKind Kind =
791 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
792 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
793
794 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000795 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000796 ExprResult Result =
797 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
798 if (Result.isInvalid())
799 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000800
Sebastian Redl14b0c192011-09-24 17:48:00 +0000801 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000802 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000803 }
John McCallfef8b342011-02-21 07:57:55 +0000804 ++Index;
805 return;
806 }
807
808 // Fall through for subaggregate initialization
809 } else {
810 // C99 6.7.8p13:
811 //
812 // The initializer for a structure or union object that has
813 // automatic storage duration shall be either an initializer
814 // list as described below, or a single expression that has
815 // compatible structure or union type. In the latter case, the
816 // initial value of the object, including unnamed members, is
817 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000818 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000819 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000820 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
821 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000822 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000823 if (ExprRes.isInvalid())
824 hadError = true;
825 else {
826 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
827 if (ExprRes.isInvalid())
828 hadError = true;
829 }
830 UpdateStructuredListElement(StructuredList, StructuredIndex,
831 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000832 ++Index;
833 return;
834 }
John Wiegley429bb272011-04-08 18:41:53 +0000835 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000836 // Fall through for subaggregate initialization
837 }
838
839 // C++ [dcl.init.aggr]p12:
840 //
841 // [...] Otherwise, if the member is itself a non-empty
842 // subaggregate, brace elision is assumed and the initializer is
843 // considered for the initialization of the first member of
844 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000845 if (!SemaRef.getLangOptions().OpenCL &&
846 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000847 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
848 StructuredIndex);
849 ++StructuredIndex;
850 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000851 if (!VerifyOnly) {
852 // We cannot initialize this element, so let
853 // PerformCopyInitialization produce the appropriate diagnostic.
854 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
855 SemaRef.Owned(expr),
856 /*TopLevelOfInitList=*/true);
857 }
John McCallfef8b342011-02-21 07:57:55 +0000858 hadError = true;
859 ++Index;
860 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000861 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000862}
863
Eli Friedman0c706c22011-09-19 23:17:44 +0000864void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
865 InitListExpr *IList, QualType DeclType,
866 unsigned &Index,
867 InitListExpr *StructuredList,
868 unsigned &StructuredIndex) {
869 assert(Index == 0 && "Index in explicit init list must be zero");
870
871 // As an extension, clang supports complex initializers, which initialize
872 // a complex number component-wise. When an explicit initializer list for
873 // a complex number contains two two initializers, this extension kicks in:
874 // it exepcts the initializer list to contain two elements convertible to
875 // the element type of the complex type. The first element initializes
876 // the real part, and the second element intitializes the imaginary part.
877
878 if (IList->getNumInits() != 2)
879 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
880 StructuredIndex);
881
882 // This is an extension in C. (The builtin _Complex type does not exist
883 // in the C++ standard.)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000884 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000885 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
886 << IList->getSourceRange();
887
888 // Initialize the complex number.
889 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
890 InitializedEntity ElementEntity =
891 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
892
893 for (unsigned i = 0; i < 2; ++i) {
894 ElementEntity.setElementIndex(Index);
895 CheckSubElementType(ElementEntity, IList, elementType, Index,
896 StructuredList, StructuredIndex);
897 }
898}
899
900
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000901void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000902 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000903 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000904 InitListExpr *StructuredList,
905 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000906 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000907 if (!VerifyOnly)
908 SemaRef.Diag(IList->getLocStart(),
909 SemaRef.getLangOptions().CPlusPlus0x ?
910 diag::warn_cxx98_compat_empty_scalar_initializer :
911 diag::err_empty_scalar_initializer)
912 << IList->getSourceRange();
913 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor4c678342009-01-28 21:54:33 +0000914 ++Index;
915 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000916 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000917 }
John McCallb934c2d2010-11-11 00:46:36 +0000918
919 Expr *expr = IList->getInit(Index);
920 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000921 if (!VerifyOnly)
922 SemaRef.Diag(SubIList->getLocStart(),
923 diag::warn_many_braces_around_scalar_init)
924 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000925
926 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
927 StructuredIndex);
928 return;
929 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000930 if (!VerifyOnly)
931 SemaRef.Diag(expr->getSourceRange().getBegin(),
932 diag::err_designator_for_scalar_init)
933 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000934 hadError = true;
935 ++Index;
936 ++StructuredIndex;
937 return;
938 }
939
Sebastian Redl14b0c192011-09-24 17:48:00 +0000940 if (VerifyOnly) {
941 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
942 hadError = true;
943 ++Index;
944 return;
945 }
946
John McCallb934c2d2010-11-11 00:46:36 +0000947 ExprResult Result =
948 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000949 SemaRef.Owned(expr),
950 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000951
952 Expr *ResultExpr = 0;
953
954 if (Result.isInvalid())
955 hadError = true; // types weren't compatible.
956 else {
957 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000958
John McCallb934c2d2010-11-11 00:46:36 +0000959 if (ResultExpr != expr) {
960 // The type was promoted, update initializer list.
961 IList->setInit(Index, ResultExpr);
962 }
963 }
964 if (hadError)
965 ++StructuredIndex;
966 else
967 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
968 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000969}
970
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000971void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
972 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000973 unsigned &Index,
974 InitListExpr *StructuredList,
975 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000976 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000977 // FIXME: It would be wonderful if we could point at the actual member. In
978 // general, it would be useful to pass location information down the stack,
979 // so that we know the location (or decl) of the "current object" being
980 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000981 if (!VerifyOnly)
982 SemaRef.Diag(IList->getLocStart(),
983 diag::err_init_reference_member_uninitialized)
984 << DeclType
985 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000986 hadError = true;
987 ++Index;
988 ++StructuredIndex;
989 return;
990 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000991
992 Expr *expr = IList->getInit(Index);
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000993 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
996 << DeclType << IList->getSourceRange();
997 hadError = true;
998 ++Index;
999 ++StructuredIndex;
1000 return;
1001 }
1002
1003 if (VerifyOnly) {
1004 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1005 hadError = true;
1006 ++Index;
1007 return;
1008 }
1009
1010 ExprResult Result =
1011 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1012 SemaRef.Owned(expr),
1013 /*TopLevelOfInitList=*/true);
1014
1015 if (Result.isInvalid())
1016 hadError = true;
1017
1018 expr = Result.takeAs<Expr>();
1019 IList->setInit(Index, expr);
1020
1021 if (hadError)
1022 ++StructuredIndex;
1023 else
1024 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1025 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001026}
1027
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001028void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001029 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001030 unsigned &Index,
1031 InitListExpr *StructuredList,
1032 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001033 const VectorType *VT = DeclType->getAs<VectorType>();
1034 unsigned maxElements = VT->getNumElements();
1035 unsigned numEltsInit = 0;
1036 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001037
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001038 if (Index >= IList->getNumInits()) {
1039 // Make sure the element type can be value-initialized.
1040 if (VerifyOnly)
1041 CheckValueInitializable(
1042 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1043 return;
1044 }
1045
John McCall20e047a2010-10-30 00:11:39 +00001046 if (!SemaRef.getLangOptions().OpenCL) {
1047 // If the initializing element is a vector, try to copy-initialize
1048 // instead of breaking it apart (which is doomed to failure anyway).
1049 Expr *Init = IList->getInit(Index);
1050 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001051 if (VerifyOnly) {
1052 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1053 hadError = true;
1054 ++Index;
1055 return;
1056 }
1057
John McCall20e047a2010-10-30 00:11:39 +00001058 ExprResult Result =
1059 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001060 SemaRef.Owned(Init),
1061 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001062
1063 Expr *ResultExpr = 0;
1064 if (Result.isInvalid())
1065 hadError = true; // types weren't compatible.
1066 else {
1067 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
John McCall20e047a2010-10-30 00:11:39 +00001069 if (ResultExpr != Init) {
1070 // The type was promoted, update initializer list.
1071 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001072 }
1073 }
John McCall20e047a2010-10-30 00:11:39 +00001074 if (hadError)
1075 ++StructuredIndex;
1076 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001077 UpdateStructuredListElement(StructuredList, StructuredIndex,
1078 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001079 ++Index;
1080 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
John McCall20e047a2010-10-30 00:11:39 +00001083 InitializedEntity ElementEntity =
1084 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
John McCall20e047a2010-10-30 00:11:39 +00001086 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1087 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001088 if (Index >= IList->getNumInits()) {
1089 if (VerifyOnly)
1090 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001091 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093
John McCall20e047a2010-10-30 00:11:39 +00001094 ElementEntity.setElementIndex(Index);
1095 CheckSubElementType(ElementEntity, IList, elementType, Index,
1096 StructuredList, StructuredIndex);
1097 }
1098 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001099 }
John McCall20e047a2010-10-30 00:11:39 +00001100
1101 InitializedEntity ElementEntity =
1102 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001103
John McCall20e047a2010-10-30 00:11:39 +00001104 // OpenCL initializers allows vectors to be constructed from vectors.
1105 for (unsigned i = 0; i < maxElements; ++i) {
1106 // Don't attempt to go past the end of the init list
1107 if (Index >= IList->getNumInits())
1108 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001109
John McCall20e047a2010-10-30 00:11:39 +00001110 ElementEntity.setElementIndex(Index);
1111
1112 QualType IType = IList->getInit(Index)->getType();
1113 if (!IType->isVectorType()) {
1114 CheckSubElementType(ElementEntity, IList, elementType, Index,
1115 StructuredList, StructuredIndex);
1116 ++numEltsInit;
1117 } else {
1118 QualType VecType;
1119 const VectorType *IVT = IType->getAs<VectorType>();
1120 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001121
John McCall20e047a2010-10-30 00:11:39 +00001122 if (IType->isExtVectorType())
1123 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1124 else
1125 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001126 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001127 CheckSubElementType(ElementEntity, IList, VecType, Index,
1128 StructuredList, StructuredIndex);
1129 numEltsInit += numIElts;
1130 }
1131 }
1132
1133 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001134 if (numEltsInit != maxElements) {
1135 if (!VerifyOnly)
1136 SemaRef.Diag(IList->getSourceRange().getBegin(),
1137 diag::err_vector_incorrect_num_initializers)
1138 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1139 hadError = true;
1140 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001141}
1142
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001143void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001144 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001145 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001146 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
1149 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001150 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1151
Steve Naroff0cca7492008-05-01 22:18:59 +00001152 // Check for the special-case of initializing an array with a string.
1153 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001154 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001155 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001156 // We place the string literal directly into the resulting
1157 // initializer list. This is the only place where the structure
1158 // of the structured initializer list doesn't match exactly,
1159 // because doing so would involve allocating one character
1160 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001161 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001162 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001163 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1164 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1165 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001166 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001167 return;
1168 }
1169 }
John McCallce6c9b72011-02-21 07:22:22 +00001170 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001171 // Check for VLAs; in standard C it would be possible to check this
1172 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1173 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001174 if (!VerifyOnly)
1175 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1176 diag::err_variable_object_no_init)
1177 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001178 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001179 ++Index;
1180 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001181 return;
1182 }
1183
Douglas Gregor05c13a32009-01-22 00:58:24 +00001184 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001185 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1186 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001188 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001189 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001190 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001191 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001192 maxElementsKnown = true;
1193 }
1194
John McCallce6c9b72011-02-21 07:22:22 +00001195 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001196 while (Index < IList->getNumInits()) {
1197 Expr *Init = IList->getInit(Index);
1198 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001199 // If we're not the subobject that matches up with the '{' for
1200 // the designator, we shouldn't be handling the
1201 // designator. Return immediately.
1202 if (!SubobjectIsDesignatorContext)
1203 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001204
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001205 // Handle this designated initializer. elementIndex will be
1206 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001207 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001208 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001209 StructuredList, StructuredIndex, true,
1210 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001211 hadError = true;
1212 continue;
1213 }
1214
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001215 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001216 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001217 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001218 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001219 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001220
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001221 // If the array is of incomplete type, keep track of the number of
1222 // elements in the initializer.
1223 if (!maxElementsKnown && elementIndex > maxElements)
1224 maxElements = elementIndex;
1225
Douglas Gregor05c13a32009-01-22 00:58:24 +00001226 continue;
1227 }
1228
1229 // If we know the maximum number of elements, and we've already
1230 // hit it, stop consuming elements in the initializer list.
1231 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001232 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001233
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001234 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001236 Entity);
1237 // Check this element.
1238 CheckSubElementType(ElementEntity, IList, elementType, Index,
1239 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001240 ++elementIndex;
1241
1242 // If the array is of incomplete type, keep track of the number of
1243 // elements in the initializer.
1244 if (!maxElementsKnown && elementIndex > maxElements)
1245 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001246 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001247 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001248 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001249 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001250 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001251 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001252 // Sizing an array implicitly to zero is not allowed by ISO C,
1253 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001254 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001255 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001256 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001257
Mike Stump1eb44332009-09-09 15:08:12 +00001258 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001259 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001260 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001261 if (!hadError && VerifyOnly) {
1262 // Check if there are any members of the array that get value-initialized.
1263 // If so, check if doing that is possible.
1264 // FIXME: This needs to detect holes left by designated initializers too.
1265 if (maxElementsKnown && elementIndex < maxElements)
1266 CheckValueInitializable(InitializedEntity::InitializeElement(
1267 SemaRef.Context, 0, Entity));
1268 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001269}
1270
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001271bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1272 Expr *InitExpr,
1273 FieldDecl *Field,
1274 bool TopLevelObject) {
1275 // Handle GNU flexible array initializers.
1276 unsigned FlexArrayDiag;
1277 if (isa<InitListExpr>(InitExpr) &&
1278 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1279 // Empty flexible array init always allowed as an extension
1280 FlexArrayDiag = diag::ext_flexible_array_init;
1281 } else if (SemaRef.getLangOptions().CPlusPlus) {
1282 // Disallow flexible array init in C++; it is not required for gcc
1283 // compatibility, and it needs work to IRGen correctly in general.
1284 FlexArrayDiag = diag::err_flexible_array_init;
1285 } else if (!TopLevelObject) {
1286 // Disallow flexible array init on non-top-level object
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1289 // Disallow flexible array init on anything which is not a variable.
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1292 // Disallow flexible array init on local variables.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else {
1295 // Allow other cases.
1296 FlexArrayDiag = diag::ext_flexible_array_init;
1297 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001298
1299 if (!VerifyOnly) {
1300 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1301 FlexArrayDiag)
1302 << InitExpr->getSourceRange().getBegin();
1303 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1304 << Field;
1305 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001306
1307 return FlexArrayDiag != diag::ext_flexible_array_init;
1308}
1309
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001310void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001311 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001312 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001313 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001314 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 unsigned &Index,
1316 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001317 unsigned &StructuredIndex,
1318 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001319 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Eli Friedmanb85f7072008-05-19 19:16:24 +00001321 // If the record is invalid, some of it's members are invalid. To avoid
1322 // confusion, we forgo checking the intializer for the entire record.
1323 if (structDecl->isInvalidDecl()) {
1324 hadError = true;
1325 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001326 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001327
1328 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001329 // Value-initialize the first named member of the union.
1330 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1331 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1332 Field != FieldEnd; ++Field) {
1333 if (Field->getDeclName()) {
1334 if (VerifyOnly)
1335 CheckValueInitializable(
1336 InitializedEntity::InitializeMember(*Field, &Entity));
1337 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001338 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001339 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001340 }
1341 }
1342 return;
1343 }
1344
Douglas Gregor05c13a32009-01-22 00:58:24 +00001345 // If structDecl is a forward declaration, this loop won't do
1346 // anything except look at designated initializers; That's okay,
1347 // because an error should get printed out elsewhere. It might be
1348 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001349 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001350 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001351 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001352 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001353 while (Index < IList->getNumInits()) {
1354 Expr *Init = IList->getInit(Index);
1355
1356 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001357 // If we're not the subobject that matches up with the '{' for
1358 // the designator, we shouldn't be handling the
1359 // designator. Return immediately.
1360 if (!SubobjectIsDesignatorContext)
1361 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001362
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001363 // Handle this designated initializer. Field will be updated to
1364 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001365 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001366 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001367 StructuredList, StructuredIndex,
1368 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001369 hadError = true;
1370
Douglas Gregordfb5e592009-02-12 19:00:39 +00001371 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001372
1373 // Disable check for missing fields when designators are used.
1374 // This matches gcc behaviour.
1375 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001376 continue;
1377 }
1378
1379 if (Field == FieldEnd) {
1380 // We've run out of fields. We're done.
1381 break;
1382 }
1383
Douglas Gregordfb5e592009-02-12 19:00:39 +00001384 // We've already initialized a member of a union. We're done.
1385 if (InitializedSomething && DeclType->isUnionType())
1386 break;
1387
Douglas Gregor44b43212008-12-11 16:49:14 +00001388 // If we've hit the flexible array member at the end, we're done.
1389 if (Field->getType()->isIncompleteArrayType())
1390 break;
1391
Douglas Gregor0bb76892009-01-29 16:53:55 +00001392 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001394 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001395 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001396 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001397
Douglas Gregor54001c12011-06-29 21:51:31 +00001398 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001399 bool InvalidUse;
1400 if (VerifyOnly)
1401 InvalidUse = !SemaRef.CanUseDecl(*Field);
1402 else
1403 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1404 IList->getInit(Index)->getLocStart());
1405 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001406 ++Index;
1407 ++Field;
1408 hadError = true;
1409 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001410 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001411
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001412 InitializedEntity MemberEntity =
1413 InitializedEntity::InitializeMember(*Field, &Entity);
1414 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1415 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001416 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001417
Sebastian Redl14b0c192011-09-24 17:48:00 +00001418 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001419 // Initialize the first field within the union.
1420 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001421 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001422
1423 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001424 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001425
John McCall80639de2010-03-11 19:32:38 +00001426 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001427 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1428 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1429 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001430 // It is possible we have one or more unnamed bitfields remaining.
1431 // Find first (if any) named field and emit warning.
1432 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1433 it != end; ++it) {
1434 if (!it->isUnnamedBitfield()) {
1435 SemaRef.Diag(IList->getSourceRange().getEnd(),
1436 diag::warn_missing_field_initializers) << it->getName();
1437 break;
1438 }
1439 }
1440 }
1441
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001442 // Check that any remaining fields can be value-initialized.
1443 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1444 !Field->getType()->isIncompleteArrayType()) {
1445 // FIXME: Should check for holes left by designated initializers too.
1446 for (; Field != FieldEnd && !hadError; ++Field) {
1447 if (!Field->isUnnamedBitfield())
1448 CheckValueInitializable(
1449 InitializedEntity::InitializeMember(*Field, &Entity));
1450 }
1451 }
1452
Mike Stump1eb44332009-09-09 15:08:12 +00001453 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001454 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001455 return;
1456
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001457 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1458 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001460 ++Index;
1461 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001462 }
1463
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001464 InitializedEntity MemberEntity =
1465 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001467 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001469 StructuredList, StructuredIndex);
1470 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001471 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001472 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001473}
Steve Naroff0cca7492008-05-01 22:18:59 +00001474
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001475/// \brief Expand a field designator that refers to a member of an
1476/// anonymous struct or union into a series of field designators that
1477/// refers to the field within the appropriate subobject.
1478///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001479static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001480 DesignatedInitExpr *DIE,
1481 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001482 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001483 typedef DesignatedInitExpr::Designator Designator;
1484
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001485 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001487 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1488 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1489 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001490 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001491 DIE->getDesignator(DesigIdx)->getDotLoc(),
1492 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1493 else
1494 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1495 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001496 assert(isa<FieldDecl>(*PI));
1497 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001498 }
1499
1500 // Expand the current designator into the set of replacement
1501 // designators, so we have a full subobject path down to where the
1502 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001503 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001504 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001505}
Mike Stump1eb44332009-09-09 15:08:12 +00001506
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001508/// corresponds to FieldName.
1509static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1510 IdentifierInfo *FieldName) {
1511 assert(AnonField->isAnonymousStructOrUnion());
1512 Decl *NextDecl = AnonField->getNextDeclInContext();
1513 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1514 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1515 return IF;
1516 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001517 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001518 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001519}
1520
Sebastian Redl14b0c192011-09-24 17:48:00 +00001521static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1522 DesignatedInitExpr *DIE) {
1523 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1524 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1525 for (unsigned I = 0; I < NumIndexExprs; ++I)
1526 IndexExprs[I] = DIE->getSubExpr(I + 1);
1527 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1528 DIE->size(), IndexExprs.data(),
1529 NumIndexExprs, DIE->getEqualOrColonLoc(),
1530 DIE->usesGNUSyntax(), DIE->getInit());
1531}
1532
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001533namespace {
1534
1535// Callback to only accept typo corrections that are for field members of
1536// the given struct or union.
1537class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1538 public:
1539 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1540 : Record(RD) {}
1541
1542 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1543 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1544 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1545 }
1546
1547 private:
1548 RecordDecl *Record;
1549};
1550
1551}
1552
Douglas Gregor05c13a32009-01-22 00:58:24 +00001553/// @brief Check the well-formedness of a C99 designated initializer.
1554///
1555/// Determines whether the designated initializer @p DIE, which
1556/// resides at the given @p Index within the initializer list @p
1557/// IList, is well-formed for a current object of type @p DeclType
1558/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001559/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001560/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001561///
1562/// @param IList The initializer list in which this designated
1563/// initializer occurs.
1564///
Douglas Gregor71199712009-04-15 04:56:10 +00001565/// @param DIE The designated initializer expression.
1566///
1567/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001568///
1569/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1570/// into which the designation in @p DIE should refer.
1571///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572/// @param NextField If non-NULL and the first designator in @p DIE is
1573/// a field, this will be set to the field declaration corresponding
1574/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001575///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576/// @param NextElementIndex If non-NULL and the first designator in @p
1577/// DIE is an array designator or GNU array-range designator, this
1578/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001579///
1580/// @param Index Index into @p IList where the designated initializer
1581/// @p DIE occurs.
1582///
Douglas Gregor4c678342009-01-28 21:54:33 +00001583/// @param StructuredList The initializer list expression that
1584/// describes all of the subobject initializers in the order they'll
1585/// actually be initialized.
1586///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001587/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001588bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001589InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001590 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001591 DesignatedInitExpr *DIE,
1592 unsigned DesigIdx,
1593 QualType &CurrentObjectType,
1594 RecordDecl::field_iterator *NextField,
1595 llvm::APSInt *NextElementIndex,
1596 unsigned &Index,
1597 InitListExpr *StructuredList,
1598 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001599 bool FinishSubobjectInit,
1600 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001601 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001602 // Check the actual initialization for the designated object type.
1603 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001604
1605 // Temporarily remove the designator expression from the
1606 // initializer list that the child calls see, so that we don't try
1607 // to re-process the designator.
1608 unsigned OldIndex = Index;
1609 IList->setInit(OldIndex, DIE->getInit());
1610
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001611 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001612 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001613
1614 // Restore the designated initializer expression in the syntactic
1615 // form of the initializer list.
1616 if (IList->getInit(OldIndex) != DIE->getInit())
1617 DIE->setInit(IList->getInit(OldIndex));
1618 IList->setInit(OldIndex, DIE);
1619
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001620 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001621 }
1622
Douglas Gregor71199712009-04-15 04:56:10 +00001623 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001624 bool IsFirstDesignator = (DesigIdx == 0);
1625 if (!VerifyOnly) {
1626 assert((IsFirstDesignator || StructuredList) &&
1627 "Need a non-designated initializer list to start from");
1628
1629 // Determine the structural initializer list that corresponds to the
1630 // current subobject.
1631 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1632 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1633 StructuredList, StructuredIndex,
1634 SourceRange(D->getStartLocation(),
1635 DIE->getSourceRange().getEnd()));
1636 assert(StructuredList && "Expected a structured initializer list");
1637 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001638
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001639 if (D->isFieldDesignator()) {
1640 // C99 6.7.8p7:
1641 //
1642 // If a designator has the form
1643 //
1644 // . identifier
1645 //
1646 // then the current object (defined below) shall have
1647 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001648 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001649 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001650 if (!RT) {
1651 SourceLocation Loc = D->getDotLoc();
1652 if (Loc.isInvalid())
1653 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001654 if (!VerifyOnly)
1655 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1656 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001657 ++Index;
1658 return true;
1659 }
1660
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 // Note: we perform a linear search of the fields here, despite
1662 // the fact that we have a faster lookup method, because we always
1663 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001664 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001665 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001667 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001668 Field = RT->getDecl()->field_begin(),
1669 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001670 for (; Field != FieldEnd; ++Field) {
1671 if (Field->isUnnamedBitfield())
1672 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673
Francois Picheta0e27f02010-12-22 03:46:10 +00001674 // If we find a field representing an anonymous field, look in the
1675 // IndirectFieldDecl that follow for the designated initializer.
1676 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1677 if (IndirectFieldDecl *IF =
1678 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001679 // In verify mode, don't modify the original.
1680 if (VerifyOnly)
1681 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001682 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1683 D = DIE->getDesignator(DesigIdx);
1684 break;
1685 }
1686 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001687 if (KnownField && KnownField == *Field)
1688 break;
1689 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001690 break;
1691
1692 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001693 }
1694
Douglas Gregor4c678342009-01-28 21:54:33 +00001695 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001696 if (VerifyOnly) {
1697 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001698 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001699 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001700
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001701 // There was no normal field in the struct with the designated
1702 // name. Perform another lookup for this name, which may find
1703 // something that we can't designate (e.g., a member function),
1704 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001705 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001706 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001707 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001708 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001709 // Name lookup didn't find anything. Determine whether this
1710 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001711 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001712 TypoCorrection Corrected = SemaRef.CorrectTypo(
1713 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001714 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, &Validator,
1715 RT->getDecl());
1716 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001717 std::string CorrectedStr(
1718 Corrected.getAsString(SemaRef.getLangOptions()));
1719 std::string CorrectedQuotedStr(
1720 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001721 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001723 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001724 << FieldName << CurrentObjectType << CorrectedQuotedStr
1725 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001727 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001728 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001729 } else {
1730 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1731 << FieldName << CurrentObjectType;
1732 ++Index;
1733 return true;
1734 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001737 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001738 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001739 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001740 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001741 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001742 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001743 ++Index;
1744 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001745 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001746
Francois Picheta0e27f02010-12-22 03:46:10 +00001747 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001748 // The replacement field comes from typo correction; find it
1749 // in the list of fields.
1750 FieldIndex = 0;
1751 Field = RT->getDecl()->field_begin();
1752 for (; Field != FieldEnd; ++Field) {
1753 if (Field->isUnnamedBitfield())
1754 continue;
1755
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001756 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001757 Field->getIdentifier() == ReplacementField->getIdentifier())
1758 break;
1759
1760 ++FieldIndex;
1761 }
1762 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001763 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001764
1765 // All of the fields of a union are located at the same place in
1766 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001767 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001768 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001769 if (!VerifyOnly)
1770 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001771 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001772
Douglas Gregor54001c12011-06-29 21:51:31 +00001773 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001774 bool InvalidUse;
1775 if (VerifyOnly)
1776 InvalidUse = !SemaRef.CanUseDecl(*Field);
1777 else
1778 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1779 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001780 ++Index;
1781 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001782 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001783
Sebastian Redl14b0c192011-09-24 17:48:00 +00001784 if (!VerifyOnly) {
1785 // Update the designator with the field declaration.
1786 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Sebastian Redl14b0c192011-09-24 17:48:00 +00001788 // Make sure that our non-designated initializer list has space
1789 // for a subobject corresponding to this field.
1790 if (FieldIndex >= StructuredList->getNumInits())
1791 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1792 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001793
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001794 // This designator names a flexible array member.
1795 if (Field->getType()->isIncompleteArrayType()) {
1796 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001797 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001798 // We can't designate an object within the flexible array
1799 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001800 if (!VerifyOnly) {
1801 DesignatedInitExpr::Designator *NextD
1802 = DIE->getDesignator(DesigIdx + 1);
1803 SemaRef.Diag(NextD->getStartLocation(),
1804 diag::err_designator_into_flexible_array_member)
1805 << SourceRange(NextD->getStartLocation(),
1806 DIE->getSourceRange().getEnd());
1807 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1808 << *Field;
1809 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001810 Invalid = true;
1811 }
1812
Chris Lattner9046c222010-10-10 17:49:49 +00001813 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1814 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001815 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001816 if (!VerifyOnly) {
1817 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1818 diag::err_flexible_array_init_needs_braces)
1819 << DIE->getInit()->getSourceRange();
1820 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1821 << *Field;
1822 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001823 Invalid = true;
1824 }
1825
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001826 // Check GNU flexible array initializer.
1827 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1828 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001829 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001830
1831 if (Invalid) {
1832 ++Index;
1833 return true;
1834 }
1835
1836 // Initialize the array.
1837 bool prevHadError = hadError;
1838 unsigned newStructuredIndex = FieldIndex;
1839 unsigned OldIndex = Index;
1840 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001841
1842 InitializedEntity MemberEntity =
1843 InitializedEntity::InitializeMember(*Field, &Entity);
1844 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001845 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001846
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001847 IList->setInit(OldIndex, DIE);
1848 if (hadError && !prevHadError) {
1849 ++Field;
1850 ++FieldIndex;
1851 if (NextField)
1852 *NextField = Field;
1853 StructuredIndex = FieldIndex;
1854 return true;
1855 }
1856 } else {
1857 // Recurse to check later designated subobjects.
1858 QualType FieldType = (*Field)->getType();
1859 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001860
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001861 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001862 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1864 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001865 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001866 true, false))
1867 return true;
1868 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001869
1870 // Find the position of the next field to be initialized in this
1871 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001872 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001873 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001874
1875 // If this the first designator, our caller will continue checking
1876 // the rest of this struct/class/union subobject.
1877 if (IsFirstDesignator) {
1878 if (NextField)
1879 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001880 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001881 return false;
1882 }
1883
Douglas Gregor34e79462009-01-28 23:36:17 +00001884 if (!FinishSubobjectInit)
1885 return false;
1886
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001887 // We've already initialized something in the union; we're done.
1888 if (RT->getDecl()->isUnion())
1889 return hadError;
1890
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001891 // Check the remaining fields within this class/struct/union subobject.
1892 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001894 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001895 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001896 return hadError && !prevHadError;
1897 }
1898
1899 // C99 6.7.8p6:
1900 //
1901 // If a designator has the form
1902 //
1903 // [ constant-expression ]
1904 //
1905 // then the current object (defined below) shall have array
1906 // type and the expression shall be an integer constant
1907 // expression. If the array is of unknown size, any
1908 // nonnegative value is valid.
1909 //
1910 // Additionally, cope with the GNU extension that permits
1911 // designators of the form
1912 //
1913 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001914 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001915 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001916 if (!VerifyOnly)
1917 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1918 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001919 ++Index;
1920 return true;
1921 }
1922
1923 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001924 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1925 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001926 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001927 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001928 DesignatedEndIndex = DesignatedStartIndex;
1929 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001930 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001931
Mike Stump1eb44332009-09-09 15:08:12 +00001932 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001933 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001934 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001935 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001936 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001937
Chris Lattnere0fd8322011-02-19 22:28:58 +00001938 // Codegen can't handle evaluating array range designators that have side
1939 // effects, because we replicate the AST value for each initialized element.
1940 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1941 // elements with something that has a side effect, so codegen can emit an
1942 // "error unsupported" error instead of miscompiling the app.
1943 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001944 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001945 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001946 }
1947
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001948 if (isa<ConstantArrayType>(AT)) {
1949 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001950 DesignatedStartIndex
1951 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001952 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001953 DesignatedEndIndex
1954 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001955 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1956 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001957 if (!VerifyOnly)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001958 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1959 diag::err_array_designator_too_large)
1960 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1961 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001962 ++Index;
1963 return true;
1964 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001965 } else {
1966 // Make sure the bit-widths and signedness match.
1967 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001968 DesignatedEndIndex
1969 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001970 else if (DesignatedStartIndex.getBitWidth() <
1971 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001972 DesignatedStartIndex
1973 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001974 DesignatedStartIndex.setIsUnsigned(true);
1975 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Douglas Gregor4c678342009-01-28 21:54:33 +00001978 // Make sure that our non-designated initializer list has space
1979 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001980 if (!VerifyOnly &&
1981 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001982 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001983 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001984
Douglas Gregor34e79462009-01-28 23:36:17 +00001985 // Repeatedly perform subobject initializations in the range
1986 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001987
Douglas Gregor34e79462009-01-28 23:36:17 +00001988 // Move to the next designator
1989 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1990 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001991
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001992 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001993 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001994
Douglas Gregor34e79462009-01-28 23:36:17 +00001995 while (DesignatedStartIndex <= DesignatedEndIndex) {
1996 // Recurse to check later designated subobjects.
1997 QualType ElementType = AT->getElementType();
1998 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002000 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002001 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2002 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002003 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002004 (DesignatedStartIndex == DesignatedEndIndex),
2005 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002006 return true;
2007
2008 // Move to the next index in the array that we'll be initializing.
2009 ++DesignatedStartIndex;
2010 ElementIndex = DesignatedStartIndex.getZExtValue();
2011 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002012
2013 // If this the first designator, our caller will continue checking
2014 // the rest of this array subobject.
2015 if (IsFirstDesignator) {
2016 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002017 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002018 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002019 return false;
2020 }
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Douglas Gregor34e79462009-01-28 23:36:17 +00002022 if (!FinishSubobjectInit)
2023 return false;
2024
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002025 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002026 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002027 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002028 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002029 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002030 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002031}
2032
Douglas Gregor4c678342009-01-28 21:54:33 +00002033// Get the structured initializer list for a subobject of type
2034// @p CurrentObjectType.
2035InitListExpr *
2036InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2037 QualType CurrentObjectType,
2038 InitListExpr *StructuredList,
2039 unsigned StructuredIndex,
2040 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002041 if (VerifyOnly)
2042 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002043 Expr *ExistingInit = 0;
2044 if (!StructuredList)
2045 ExistingInit = SyntacticToSemantic[IList];
2046 else if (StructuredIndex < StructuredList->getNumInits())
2047 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Douglas Gregor4c678342009-01-28 21:54:33 +00002049 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2050 return Result;
2051
2052 if (ExistingInit) {
2053 // We are creating an initializer list that initializes the
2054 // subobjects of the current object, but there was already an
2055 // initialization that completely initialized the current
2056 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002057 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002058 // struct X { int a, b; };
2059 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002060 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002061 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2062 // designated initializer re-initializes the whole
2063 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002064 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002065 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002066 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00002067 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002068 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002069 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 << ExistingInit->getSourceRange();
2071 }
2072
Mike Stump1eb44332009-09-09 15:08:12 +00002073 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002074 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2075 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002076 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002077
Douglas Gregor63982352010-07-13 18:40:04 +00002078 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002079
Douglas Gregorfa219202009-03-20 23:58:33 +00002080 // Pre-allocate storage for the structured initializer list.
2081 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002082 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002083 bool GotNumInits = false;
2084 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002085 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002086 GotNumInits = true;
2087 } else if (Index < IList->getNumInits()) {
2088 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002089 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002090 GotNumInits = true;
2091 }
Douglas Gregor08457732009-03-21 18:13:52 +00002092 }
2093
Mike Stump1eb44332009-09-09 15:08:12 +00002094 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002095 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2096 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2097 NumElements = CAType->getSize().getZExtValue();
2098 // Simple heuristic so that we don't allocate a very large
2099 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002100 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002101 NumElements = 0;
2102 }
John McCall183700f2009-09-21 23:43:11 +00002103 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002104 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002105 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002106 RecordDecl *RDecl = RType->getDecl();
2107 if (RDecl->isUnion())
2108 NumElements = 1;
2109 else
Mike Stump1eb44332009-09-09 15:08:12 +00002110 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002111 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002112 }
2113
Ted Kremenek709210f2010-04-13 23:39:13 +00002114 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002115
Douglas Gregor4c678342009-01-28 21:54:33 +00002116 // Link this new initializer list into the structured initializer
2117 // lists.
2118 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002119 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002120 else {
2121 Result->setSyntacticForm(IList);
2122 SyntacticToSemantic[IList] = Result;
2123 }
2124
2125 return Result;
2126}
2127
2128/// Update the initializer at index @p StructuredIndex within the
2129/// structured initializer list to the value @p expr.
2130void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2131 unsigned &StructuredIndex,
2132 Expr *expr) {
2133 // No structured initializer list to update
2134 if (!StructuredList)
2135 return;
2136
Ted Kremenek709210f2010-04-13 23:39:13 +00002137 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2138 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002139 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002140 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002141 diag::warn_initializer_overrides)
2142 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002143 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002144 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002145 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002146 << PrevInit->getSourceRange();
2147 }
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Douglas Gregor4c678342009-01-28 21:54:33 +00002149 ++StructuredIndex;
2150}
2151
Douglas Gregor05c13a32009-01-22 00:58:24 +00002152/// Check that the given Index expression is a valid array designator
2153/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002154/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002155/// and produces a reasonable diagnostic if there is a
2156/// failure. Returns true if there was an error, false otherwise. If
2157/// everything went okay, Value will receive the value of the constant
2158/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002159static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002160CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002161 SourceLocation Loc = Index->getSourceRange().getBegin();
2162
2163 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002164 if (S.VerifyIntegerConstantExpression(Index, &Value))
2165 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002166
Chris Lattner3bf68932009-04-25 21:59:05 +00002167 if (Value.isSigned() && Value.isNegative())
2168 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002169 << Value.toString(10) << Index->getSourceRange();
2170
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002171 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002172 return false;
2173}
2174
John McCall60d7b3a2010-08-24 06:29:42 +00002175ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002176 SourceLocation Loc,
2177 bool GNUSyntax,
2178 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002179 typedef DesignatedInitExpr::Designator ASTDesignator;
2180
2181 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002182 SmallVector<ASTDesignator, 32> Designators;
2183 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002184
2185 // Build designators and check array designator expressions.
2186 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2187 const Designator &D = Desig.getDesignator(Idx);
2188 switch (D.getKind()) {
2189 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002190 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002191 D.getFieldLoc()));
2192 break;
2193
2194 case Designator::ArrayDesignator: {
2195 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2196 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002197 if (!Index->isTypeDependent() &&
2198 !Index->isValueDependent() &&
2199 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002200 Invalid = true;
2201 else {
2202 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002203 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002204 D.getRBracketLoc()));
2205 InitExpressions.push_back(Index);
2206 }
2207 break;
2208 }
2209
2210 case Designator::ArrayRangeDesignator: {
2211 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2212 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2213 llvm::APSInt StartValue;
2214 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002215 bool StartDependent = StartIndex->isTypeDependent() ||
2216 StartIndex->isValueDependent();
2217 bool EndDependent = EndIndex->isTypeDependent() ||
2218 EndIndex->isValueDependent();
2219 if ((!StartDependent &&
2220 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2221 (!EndDependent &&
2222 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002223 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002224 else {
2225 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002226 if (StartDependent || EndDependent) {
2227 // Nothing to compute.
2228 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002229 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002230 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002231 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002232
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002233 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002234 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002235 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002236 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2237 Invalid = true;
2238 } else {
2239 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002240 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002241 D.getEllipsisLoc(),
2242 D.getRBracketLoc()));
2243 InitExpressions.push_back(StartIndex);
2244 InitExpressions.push_back(EndIndex);
2245 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002246 }
2247 break;
2248 }
2249 }
2250 }
2251
2252 if (Invalid || Init.isInvalid())
2253 return ExprError();
2254
2255 // Clear out the expressions within the designation.
2256 Desig.ClearExprs(*this);
2257
2258 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002259 = DesignatedInitExpr::Create(Context,
2260 Designators.data(), Designators.size(),
2261 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002262 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263
Richard Smithd7c56e12011-12-29 21:57:33 +00002264 if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002265 Diag(DIE->getLocStart(), diag::ext_designated_init)
2266 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002267
Douglas Gregor05c13a32009-01-22 00:58:24 +00002268 return Owned(DIE);
2269}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002270
Douglas Gregor20093b42009-12-09 23:02:17 +00002271//===----------------------------------------------------------------------===//
2272// Initialization entity
2273//===----------------------------------------------------------------------===//
2274
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002275InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002276 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002278{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002279 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2280 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002281 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002282 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002283 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002284 Type = VT->getElementType();
2285 } else {
2286 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2287 assert(CT && "Unexpected type");
2288 Kind = EK_ComplexElement;
2289 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002290 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002291}
2292
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002293InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002294 CXXBaseSpecifier *Base,
2295 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002296{
2297 InitializedEntity Result;
2298 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002299 Result.Base = reinterpret_cast<uintptr_t>(Base);
2300 if (IsInheritedVirtualBase)
2301 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002302
Douglas Gregord6542d82009-12-22 15:35:07 +00002303 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 return Result;
2305}
2306
Douglas Gregor99a2e602009-12-16 01:38:02 +00002307DeclarationName InitializedEntity::getName() const {
2308 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002309 case EK_Parameter: {
2310 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2311 return (D ? D->getDeclName() : DeclarationName());
2312 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002313
2314 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002315 case EK_Member:
2316 return VariableOrMember->getDeclName();
2317
2318 case EK_Result:
2319 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002320 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002321 case EK_Temporary:
2322 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002323 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002324 case EK_ArrayElement:
2325 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002326 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002327 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002328 return DeclarationName();
2329 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330
David Blaikie7530c032012-01-17 06:56:22 +00002331 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002332}
2333
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002334DeclaratorDecl *InitializedEntity::getDecl() const {
2335 switch (getKind()) {
2336 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002337 case EK_Member:
2338 return VariableOrMember;
2339
John McCallf85e1932011-06-15 23:02:42 +00002340 case EK_Parameter:
2341 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2342
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002343 case EK_Result:
2344 case EK_Exception:
2345 case EK_New:
2346 case EK_Temporary:
2347 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002348 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002349 case EK_ArrayElement:
2350 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002351 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002352 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002353 return 0;
2354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002355
David Blaikie7530c032012-01-17 06:56:22 +00002356 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002357}
2358
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002359bool InitializedEntity::allowsNRVO() const {
2360 switch (getKind()) {
2361 case EK_Result:
2362 case EK_Exception:
2363 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002365 case EK_Variable:
2366 case EK_Parameter:
2367 case EK_Member:
2368 case EK_New:
2369 case EK_Temporary:
2370 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002371 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002372 case EK_ArrayElement:
2373 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002374 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002375 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002376 break;
2377 }
2378
2379 return false;
2380}
2381
Douglas Gregor20093b42009-12-09 23:02:17 +00002382//===----------------------------------------------------------------------===//
2383// Initialization sequence
2384//===----------------------------------------------------------------------===//
2385
2386void InitializationSequence::Step::Destroy() {
2387 switch (Kind) {
2388 case SK_ResolveAddressOfOverloadedFunction:
2389 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002390 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002391 case SK_CastDerivedToBaseLValue:
2392 case SK_BindReference:
2393 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002394 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002395 case SK_UserConversion:
2396 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002397 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002399 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002400 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002401 case SK_UnwrapInitList:
2402 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002403 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002404 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002405 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002406 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002407 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002408 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002409 case SK_PassByIndirectCopyRestore:
2410 case SK_PassByIndirectRestore:
2411 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002412 case SK_StdInitializerList:
Douglas Gregor20093b42009-12-09 23:02:17 +00002413 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002414
Douglas Gregor20093b42009-12-09 23:02:17 +00002415 case SK_ConversionSequence:
2416 delete ICS;
2417 }
2418}
2419
Douglas Gregorb70cf442010-03-26 20:14:36 +00002420bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002421 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002422}
2423
2424bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002425 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002426 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002427
Douglas Gregorb70cf442010-03-26 20:14:36 +00002428 switch (getFailureKind()) {
2429 case FK_TooManyInitsForReference:
2430 case FK_ArrayNeedsInitList:
2431 case FK_ArrayNeedsInitListOrStringLiteral:
2432 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2433 case FK_NonConstLValueReferenceBindingToTemporary:
2434 case FK_NonConstLValueReferenceBindingToUnrelated:
2435 case FK_RValueReferenceBindingToLValue:
2436 case FK_ReferenceInitDropsQualifiers:
2437 case FK_ReferenceInitFailed:
2438 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002439 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002440 case FK_TooManyInitsForScalar:
2441 case FK_ReferenceBindingToInitList:
2442 case FK_InitListBadDestinationType:
2443 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002444 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002445 case FK_ArrayTypeMismatch:
2446 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002447 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002448 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002449 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002450 case FK_InitListElementCopyFailure:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002451 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002452
Douglas Gregorb70cf442010-03-26 20:14:36 +00002453 case FK_ReferenceInitOverloadFailed:
2454 case FK_UserConversionOverloadFailed:
2455 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002456 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002457 return FailedOverloadResult == OR_Ambiguous;
2458 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002459
David Blaikie7530c032012-01-17 06:56:22 +00002460 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002461}
2462
Douglas Gregord6e44a32010-04-16 22:09:46 +00002463bool InitializationSequence::isConstructorInitialization() const {
2464 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2465}
2466
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002467void
2468InitializationSequence
2469::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2470 DeclAccessPair Found,
2471 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 Step S;
2473 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2474 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002475 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002476 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002477 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002478 Steps.push_back(S);
2479}
2480
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002481void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002482 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002483 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002484 switch (VK) {
2485 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2486 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2487 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002488 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002489 S.Type = BaseType;
2490 Steps.push_back(S);
2491}
2492
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002493void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002494 bool BindingTemporary) {
2495 Step S;
2496 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2497 S.Type = T;
2498 Steps.push_back(S);
2499}
2500
Douglas Gregor523d46a2010-04-18 07:40:54 +00002501void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2502 Step S;
2503 S.Kind = SK_ExtraneousCopyToTemporary;
2504 S.Type = T;
2505 Steps.push_back(S);
2506}
2507
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002508void
2509InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2510 DeclAccessPair FoundDecl,
2511 QualType T,
2512 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002513 Step S;
2514 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002515 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002516 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002517 S.Function.Function = Function;
2518 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002519 Steps.push_back(S);
2520}
2521
2522void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002523 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002524 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002525 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002526 switch (VK) {
2527 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002528 S.Kind = SK_QualificationConversionRValue;
2529 break;
John McCall5baba9d2010-08-25 10:28:54 +00002530 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002531 S.Kind = SK_QualificationConversionXValue;
2532 break;
John McCall5baba9d2010-08-25 10:28:54 +00002533 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002534 S.Kind = SK_QualificationConversionLValue;
2535 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002536 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002537 S.Type = Ty;
2538 Steps.push_back(S);
2539}
2540
2541void InitializationSequence::AddConversionSequenceStep(
2542 const ImplicitConversionSequence &ICS,
2543 QualType T) {
2544 Step S;
2545 S.Kind = SK_ConversionSequence;
2546 S.Type = T;
2547 S.ICS = new ImplicitConversionSequence(ICS);
2548 Steps.push_back(S);
2549}
2550
Douglas Gregord87b61f2009-12-10 17:56:55 +00002551void InitializationSequence::AddListInitializationStep(QualType T) {
2552 Step S;
2553 S.Kind = SK_ListInitialization;
2554 S.Type = T;
2555 Steps.push_back(S);
2556}
2557
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002558void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002559InitializationSequence
2560::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2561 AccessSpecifier Access,
2562 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002563 bool HadMultipleCandidates,
2564 bool FromInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002565 Step S;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002566 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002567 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002568 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002569 S.Function.Function = Constructor;
2570 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002571 Steps.push_back(S);
2572}
2573
Douglas Gregor71d17402009-12-15 00:01:57 +00002574void InitializationSequence::AddZeroInitializationStep(QualType T) {
2575 Step S;
2576 S.Kind = SK_ZeroInitialization;
2577 S.Type = T;
2578 Steps.push_back(S);
2579}
2580
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002581void InitializationSequence::AddCAssignmentStep(QualType T) {
2582 Step S;
2583 S.Kind = SK_CAssignment;
2584 S.Type = T;
2585 Steps.push_back(S);
2586}
2587
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002588void InitializationSequence::AddStringInitStep(QualType T) {
2589 Step S;
2590 S.Kind = SK_StringInit;
2591 S.Type = T;
2592 Steps.push_back(S);
2593}
2594
Douglas Gregor569c3162010-08-07 11:51:51 +00002595void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2596 Step S;
2597 S.Kind = SK_ObjCObjectConversion;
2598 S.Type = T;
2599 Steps.push_back(S);
2600}
2601
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002602void InitializationSequence::AddArrayInitStep(QualType T) {
2603 Step S;
2604 S.Kind = SK_ArrayInit;
2605 S.Type = T;
2606 Steps.push_back(S);
2607}
2608
John McCallf85e1932011-06-15 23:02:42 +00002609void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2610 bool shouldCopy) {
2611 Step s;
2612 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2613 : SK_PassByIndirectRestore);
2614 s.Type = type;
2615 Steps.push_back(s);
2616}
2617
2618void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2619 Step S;
2620 S.Kind = SK_ProduceObjCObject;
2621 S.Type = T;
2622 Steps.push_back(S);
2623}
2624
Sebastian Redl2b916b82012-01-17 22:49:42 +00002625void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2626 Step S;
2627 S.Kind = SK_StdInitializerList;
2628 S.Type = T;
2629 Steps.push_back(S);
2630}
2631
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002632void InitializationSequence::RewrapReferenceInitList(QualType T,
2633 InitListExpr *Syntactic) {
2634 assert(Syntactic->getNumInits() == 1 &&
2635 "Can only rewrap trivial init lists.");
2636 Step S;
2637 S.Kind = SK_UnwrapInitList;
2638 S.Type = Syntactic->getInit(0)->getType();
2639 Steps.insert(Steps.begin(), S);
2640
2641 S.Kind = SK_RewrapInitList;
2642 S.Type = T;
2643 S.WrappingSyntacticList = Syntactic;
2644 Steps.push_back(S);
2645}
2646
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002647void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002648 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002649 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002650 this->Failure = Failure;
2651 this->FailedOverloadResult = Result;
2652}
2653
2654//===----------------------------------------------------------------------===//
2655// Attempt initialization
2656//===----------------------------------------------------------------------===//
2657
John McCallf85e1932011-06-15 23:02:42 +00002658static void MaybeProduceObjCObject(Sema &S,
2659 InitializationSequence &Sequence,
2660 const InitializedEntity &Entity) {
2661 if (!S.getLangOptions().ObjCAutoRefCount) return;
2662
2663 /// When initializing a parameter, produce the value if it's marked
2664 /// __attribute__((ns_consumed)).
2665 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2666 if (!Entity.isParameterConsumed())
2667 return;
2668
2669 assert(Entity.getType()->isObjCRetainableType() &&
2670 "consuming an object of unretainable type?");
2671 Sequence.AddProduceObjCObjectStep(Entity.getType());
2672
2673 /// When initializing a return value, if the return type is a
2674 /// retainable type, then returns need to immediately retain the
2675 /// object. If an autorelease is required, it will be done at the
2676 /// last instant.
2677 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2678 if (!Entity.getType()->isObjCRetainableType())
2679 return;
2680
2681 Sequence.AddProduceObjCObjectStep(Entity.getType());
2682 }
2683}
2684
Sebastian Redl10f04a62011-12-22 14:44:04 +00002685/// \brief When initializing from init list via constructor, deal with the
2686/// empty init list and std::initializer_list special cases.
2687///
2688/// \return True if this was a special case, false otherwise.
2689static bool TryListConstructionSpecialCases(Sema &S,
2690 Expr **Args, unsigned NumArgs,
2691 CXXRecordDecl *DestRecordDecl,
2692 QualType DestType,
2693 InitializationSequence &Sequence) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002694 // C++11 [dcl.init.list]p3:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002695 // List-initialization of an object of type T is defined as follows:
2696 // - If the initializer list has no elements and T is a class type with
2697 // a default constructor, the object is value-initialized.
2698 if (NumArgs == 0) {
2699 if (CXXConstructorDecl *DefaultConstructor =
2700 S.LookupDefaultConstructor(DestRecordDecl)) {
2701 if (DefaultConstructor->isDeleted() ||
2702 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2703 // Fake an overload resolution failure.
2704 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2705 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2706 DefaultConstructor->getAccess());
2707 if (FunctionTemplateDecl *ConstructorTmpl =
2708 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2709 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2710 /*ExplicitArgs*/ 0,
2711 Args, NumArgs, CandidateSet,
2712 /*SuppressUserConversions*/ false);
2713 else
2714 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2715 Args, NumArgs, CandidateSet,
2716 /*SuppressUserConversions*/ false);
2717 Sequence.SetOverloadFailure(
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002718 InitializationSequence::FK_ListConstructorOverloadFailed,
2719 OR_Deleted);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002720 } else
2721 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2722 DefaultConstructor->getAccess(),
2723 DestType,
2724 /*MultipleCandidates=*/false,
2725 /*FromInitList=*/true);
2726 return true;
2727 }
2728 }
2729
2730 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redl2b916b82012-01-17 22:49:42 +00002731 QualType E;
2732 if (S.isStdInitializerList(DestType, &E)) {
2733 // Check that each individual element can be copy-constructed. But since we
2734 // have no place to store further information, we'll recalculate everything
2735 // later.
2736 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2737 S.Context.getConstantArrayType(E,
2738 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),NumArgs),
2739 ArrayType::Normal, 0));
2740 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2741 0, HiddenArray);
2742 for (unsigned i = 0; i < NumArgs; ++i) {
2743 Element.setElementIndex(i);
2744 if (!S.CanPerformCopyInitialization(Element, Args[i])) {
2745 Sequence.SetFailed(
2746 InitializationSequence::FK_InitListElementCopyFailure);
2747 return true;
2748 }
2749 }
2750 Sequence.AddStdInitializerListConstructionStep(DestType);
2751 return true;
2752 }
Sebastian Redl10f04a62011-12-22 14:44:04 +00002753
2754 // Not a special case.
2755 return false;
2756}
2757
2758/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2759/// enumerates the constructors of the initialized entity and performs overload
2760/// resolution to select the best.
2761/// If FromInitList is true, this is list-initialization of a non-aggregate
2762/// class type.
2763static void TryConstructorInitialization(Sema &S,
2764 const InitializedEntity &Entity,
2765 const InitializationKind &Kind,
2766 Expr **Args, unsigned NumArgs,
2767 QualType DestType,
2768 InitializationSequence &Sequence,
2769 bool FromInitList = false) {
2770 // Check constructor arguments for self reference.
2771 if (DeclaratorDecl *DD = Entity.getDecl())
2772 // Parameters arguments are occassionially constructed with itself,
2773 // for instance, in recursive functions. Skip them.
2774 if (!isa<ParmVarDecl>(DD))
2775 for (unsigned i = 0; i < NumArgs; ++i)
2776 S.CheckSelfReference(DD, Args[i]);
2777
2778 // Build the candidate set directly in the initialization sequence
2779 // structure, so that it will persist if we fail.
2780 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2781 CandidateSet.clear();
2782
2783 // Determine whether we are allowed to call explicit constructors or
2784 // explicit conversion operators.
2785 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2786 Kind.getKind() == InitializationKind::IK_Value ||
2787 Kind.getKind() == InitializationKind::IK_Default);
2788
2789 // The type we're constructing needs to be complete.
2790 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2791 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2792 }
2793
2794 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2795 assert(DestRecordType && "Constructor initialization requires record type");
2796 CXXRecordDecl *DestRecordDecl
2797 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2798
2799 if (FromInitList &&
2800 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2801 DestType, Sequence))
2802 return;
2803
2804 // - Otherwise, if T is a class type, constructors are considered. The
2805 // applicable constructors are enumerated, and the best one is chosen
2806 // through overload resolution.
2807 DeclContext::lookup_iterator Con, ConEnd;
2808 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2809 Con != ConEnd; ++Con) {
2810 NamedDecl *D = *Con;
2811 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2812 bool SuppressUserConversions = false;
2813
2814 // Find the constructor (which may be a template).
2815 CXXConstructorDecl *Constructor = 0;
2816 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2817 if (ConstructorTmpl)
2818 Constructor = cast<CXXConstructorDecl>(
2819 ConstructorTmpl->getTemplatedDecl());
2820 else {
2821 Constructor = cast<CXXConstructorDecl>(D);
2822
2823 // If we're performing copy initialization using a copy constructor, we
2824 // suppress user-defined conversions on the arguments.
2825 // FIXME: Move constructors?
2826 if (Kind.getKind() == InitializationKind::IK_Copy &&
2827 Constructor->isCopyConstructor())
2828 SuppressUserConversions = true;
2829 }
2830
2831 if (!Constructor->isInvalidDecl() &&
2832 (AllowExplicit || !Constructor->isExplicit())) {
2833 if (ConstructorTmpl)
2834 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2835 /*ExplicitArgs*/ 0,
2836 Args, NumArgs, CandidateSet,
2837 SuppressUserConversions);
2838 else
2839 S.AddOverloadCandidate(Constructor, FoundDecl,
2840 Args, NumArgs, CandidateSet,
2841 SuppressUserConversions);
2842 }
2843 }
2844
2845 SourceLocation DeclLoc = Kind.getLocation();
2846
2847 // Perform overload resolution. If it fails, return the failed result.
2848 OverloadCandidateSet::iterator Best;
2849 if (OverloadingResult Result
2850 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002851 Sequence.SetOverloadFailure(FromInitList ?
2852 InitializationSequence::FK_ListConstructorOverloadFailed :
2853 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002854 Result);
2855 return;
2856 }
2857
2858 // C++0x [dcl.init]p6:
2859 // If a program calls for the default initialization of an object
2860 // of a const-qualified type T, T shall be a class type with a
2861 // user-provided default constructor.
2862 if (Kind.getKind() == InitializationKind::IK_Default &&
2863 Entity.getType().isConstQualified() &&
2864 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2865 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2866 return;
2867 }
2868
2869 // Add the constructor initialization step. Any cv-qualification conversion is
2870 // subsumed by the initialization.
2871 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2872 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2873 Sequence.AddConstructorInitializationStep(CtorDecl,
2874 Best->FoundDecl.getAccess(),
2875 DestType, HadMultipleCandidates,
2876 FromInitList);
2877}
2878
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002879static bool
2880ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2881 Expr *Initializer,
2882 QualType &SourceType,
2883 QualType &UnqualifiedSourceType,
2884 QualType UnqualifiedTargetType,
2885 InitializationSequence &Sequence) {
2886 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2887 S.Context.OverloadTy) {
2888 DeclAccessPair Found;
2889 bool HadMultipleCandidates = false;
2890 if (FunctionDecl *Fn
2891 = S.ResolveAddressOfOverloadedFunction(Initializer,
2892 UnqualifiedTargetType,
2893 false, Found,
2894 &HadMultipleCandidates)) {
2895 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2896 HadMultipleCandidates);
2897 SourceType = Fn->getType();
2898 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2899 } else if (!UnqualifiedTargetType->isRecordType()) {
2900 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2901 return true;
2902 }
2903 }
2904 return false;
2905}
2906
2907static void TryReferenceInitializationCore(Sema &S,
2908 const InitializedEntity &Entity,
2909 const InitializationKind &Kind,
2910 Expr *Initializer,
2911 QualType cv1T1, QualType T1,
2912 Qualifiers T1Quals,
2913 QualType cv2T2, QualType T2,
2914 Qualifiers T2Quals,
2915 InitializationSequence &Sequence);
2916
2917static void TryListInitialization(Sema &S,
2918 const InitializedEntity &Entity,
2919 const InitializationKind &Kind,
2920 InitListExpr *InitList,
2921 InitializationSequence &Sequence);
2922
2923/// \brief Attempt list initialization of a reference.
2924static void TryReferenceListInitialization(Sema &S,
2925 const InitializedEntity &Entity,
2926 const InitializationKind &Kind,
2927 InitListExpr *InitList,
2928 InitializationSequence &Sequence)
2929{
2930 // First, catch C++03 where this isn't possible.
2931 if (!S.getLangOptions().CPlusPlus0x) {
2932 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2933 return;
2934 }
2935
2936 QualType DestType = Entity.getType();
2937 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2938 Qualifiers T1Quals;
2939 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2940
2941 // Reference initialization via an initializer list works thus:
2942 // If the initializer list consists of a single element that is
2943 // reference-related to the referenced type, bind directly to that element
2944 // (possibly creating temporaries).
2945 // Otherwise, initialize a temporary with the initializer list and
2946 // bind to that.
2947 if (InitList->getNumInits() == 1) {
2948 Expr *Initializer = InitList->getInit(0);
2949 QualType cv2T2 = Initializer->getType();
2950 Qualifiers T2Quals;
2951 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2952
2953 // If this fails, creating a temporary wouldn't work either.
2954 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
2955 T1, Sequence))
2956 return;
2957
2958 SourceLocation DeclLoc = Initializer->getLocStart();
2959 bool dummy1, dummy2, dummy3;
2960 Sema::ReferenceCompareResult RefRelationship
2961 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
2962 dummy2, dummy3);
2963 if (RefRelationship >= Sema::Ref_Related) {
2964 // Try to bind the reference here.
2965 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
2966 T1Quals, cv2T2, T2, T2Quals, Sequence);
2967 if (Sequence)
2968 Sequence.RewrapReferenceInitList(cv1T1, InitList);
2969 return;
2970 }
2971 }
2972
2973 // Not reference-related. Create a temporary and bind to that.
2974 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2975
2976 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
2977 if (Sequence) {
2978 if (DestType->isRValueReferenceType() ||
2979 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
2980 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2981 else
2982 Sequence.SetFailed(
2983 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2984 }
2985}
2986
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002987/// \brief Attempt list initialization (C++0x [dcl.init.list])
2988static void TryListInitialization(Sema &S,
2989 const InitializedEntity &Entity,
2990 const InitializationKind &Kind,
2991 InitListExpr *InitList,
2992 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002993 QualType DestType = Entity.getType();
2994
Sebastian Redl14b0c192011-09-24 17:48:00 +00002995 // C++ doesn't allow scalar initialization with more than one argument.
2996 // But C99 complex numbers are scalars and it makes sense there.
2997 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2998 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2999 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3000 return;
3001 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003002 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003003 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003004 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003005 }
3006 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003007 if (S.getLangOptions().CPlusPlus0x)
3008 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3009 InitList->getNumInits(), DestType, Sequence,
3010 /*FromInitList=*/true);
3011 else
3012 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003013 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003014 }
3015
Sebastian Redl14b0c192011-09-24 17:48:00 +00003016 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003017 DestType, /*VerifyOnly=*/true,
3018 Kind.getKind() != InitializationKind::IK_Direct ||
3019 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003020 if (CheckInitList.HadError()) {
3021 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3022 return;
3023 }
3024
3025 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003026 Sequence.AddListInitializationStep(DestType);
3027}
Douglas Gregor20093b42009-12-09 23:02:17 +00003028
3029/// \brief Try a reference initialization that involves calling a conversion
3030/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003031static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3032 const InitializedEntity &Entity,
3033 const InitializationKind &Kind,
3034 Expr *Initializer,
3035 bool AllowRValues,
3036 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003037 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003038 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3039 QualType T1 = cv1T1.getUnqualifiedType();
3040 QualType cv2T2 = Initializer->getType();
3041 QualType T2 = cv2T2.getUnqualifiedType();
3042
3043 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003044 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003045 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003047 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003048 ObjCConversion,
3049 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003050 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003051 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003052 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003053 (void)ObjCLifetimeConversion;
3054
Douglas Gregor20093b42009-12-09 23:02:17 +00003055 // Build the candidate set directly in the initialization sequence
3056 // structure, so that it will persist if we fail.
3057 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3058 CandidateSet.clear();
3059
3060 // Determine whether we are allowed to call explicit constructors or
3061 // explicit conversion operators.
3062 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063
Douglas Gregor20093b42009-12-09 23:02:17 +00003064 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003065 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3066 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003067 // The type we're converting to is a class type. Enumerate its constructors
3068 // to see if there is a suitable conversion.
3069 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003070
Douglas Gregor20093b42009-12-09 23:02:17 +00003071 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003072 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00003073 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003074 NamedDecl *D = *Con;
3075 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3076
Douglas Gregor20093b42009-12-09 23:02:17 +00003077 // Find the constructor (which may be a template).
3078 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003079 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003080 if (ConstructorTmpl)
3081 Constructor = cast<CXXConstructorDecl>(
3082 ConstructorTmpl->getTemplatedDecl());
3083 else
John McCall9aa472c2010-03-19 07:35:19 +00003084 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085
Douglas Gregor20093b42009-12-09 23:02:17 +00003086 if (!Constructor->isInvalidDecl() &&
3087 Constructor->isConvertingConstructor(AllowExplicit)) {
3088 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003089 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003090 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003091 &Initializer, 1, CandidateSet,
3092 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003093 else
John McCall9aa472c2010-03-19 07:35:19 +00003094 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003095 &Initializer, 1, CandidateSet,
3096 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003097 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003098 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003099 }
John McCall572fc622010-08-17 07:23:57 +00003100 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3101 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003102
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003103 const RecordType *T2RecordType = 0;
3104 if ((T2RecordType = T2->getAs<RecordType>()) &&
3105 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003106 // The type we're converting from is a class type, enumerate its conversion
3107 // functions.
3108 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3109
John McCalleec51cf2010-01-20 00:46:10 +00003110 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00003111 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003112 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3113 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003114 NamedDecl *D = *I;
3115 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3116 if (isa<UsingShadowDecl>(D))
3117 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118
Douglas Gregor20093b42009-12-09 23:02:17 +00003119 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3120 CXXConversionDecl *Conv;
3121 if (ConvTemplate)
3122 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3123 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003124 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003125
Douglas Gregor20093b42009-12-09 23:02:17 +00003126 // If the conversion function doesn't return a reference type,
3127 // it can't be considered for this conversion unless we're allowed to
3128 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003129 // FIXME: Do we need to make sure that we only consider conversion
3130 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003131 // break recursion.
3132 if ((AllowExplicit || !Conv->isExplicit()) &&
3133 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3134 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003135 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003136 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003137 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003138 else
John McCall9aa472c2010-03-19 07:35:19 +00003139 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003140 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003141 }
3142 }
3143 }
John McCall572fc622010-08-17 07:23:57 +00003144 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3145 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003146
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 SourceLocation DeclLoc = Initializer->getLocStart();
3148
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003150 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003151 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003152 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003153 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003154
Douglas Gregor20093b42009-12-09 23:02:17 +00003155 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003156
Chandler Carruth25ca4212011-02-25 19:41:05 +00003157 // This is the overload that will actually be used for the initialization, so
3158 // mark it as used.
3159 S.MarkDeclarationReferenced(DeclLoc, Function);
3160
Eli Friedman03981012009-12-11 02:42:07 +00003161 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003162 if (isa<CXXConversionDecl>(Function))
3163 T2 = Function->getResultType();
3164 else
3165 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003166
3167 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003168 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003169 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003170 T2.getNonLValueExprType(S.Context),
3171 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003172
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003174 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003175 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003176 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003177 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003178 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003179 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003180
Douglas Gregor20093b42009-12-09 23:02:17 +00003181 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003182 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003183 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003184 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003185 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003186 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003187 NewDerivedToBase, NewObjCConversion,
3188 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003189 if (NewRefRelationship == Sema::Ref_Incompatible) {
3190 // If the type we've converted to is not reference-related to the
3191 // type we're looking for, then there is another conversion step
3192 // we need to perform to produce a temporary of the right type
3193 // that we'll be binding to.
3194 ImplicitConversionSequence ICS;
3195 ICS.setStandard();
3196 ICS.Standard = Best->FinalConversion;
3197 T2 = ICS.Standard.getToType(2);
3198 Sequence.AddConversionSequenceStep(ICS, T2);
3199 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003200 Sequence.AddDerivedToBaseCastStep(
3201 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003203 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003204 else if (NewObjCConversion)
3205 Sequence.AddObjCObjectConversionStep(
3206 S.Context.getQualifiedType(T1,
3207 T2.getNonReferenceType().getQualifiers()));
3208
Douglas Gregor20093b42009-12-09 23:02:17 +00003209 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003210 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211
Douglas Gregor20093b42009-12-09 23:02:17 +00003212 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3213 return OR_Success;
3214}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
Richard Smith83da2e72011-10-19 16:55:56 +00003216static void CheckCXX98CompatAccessibleCopy(Sema &S,
3217 const InitializedEntity &Entity,
3218 Expr *CurInitExpr);
3219
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3221static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003222 const InitializedEntity &Entity,
3223 const InitializationKind &Kind,
3224 Expr *Initializer,
3225 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003226 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003227 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003228 Qualifiers T1Quals;
3229 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003230 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003231 Qualifiers T2Quals;
3232 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003233
Douglas Gregor20093b42009-12-09 23:02:17 +00003234 // If the initializer is the address of an overloaded function, try
3235 // to resolve the overloaded function. If all goes well, T2 is the
3236 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003237 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3238 T1, Sequence))
3239 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003240
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003241 // Delegate everything else to a subfunction.
3242 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3243 T1Quals, cv2T2, T2, T2Quals, Sequence);
3244}
3245
3246/// \brief Reference initialization without resolving overloaded functions.
3247static void TryReferenceInitializationCore(Sema &S,
3248 const InitializedEntity &Entity,
3249 const InitializationKind &Kind,
3250 Expr *Initializer,
3251 QualType cv1T1, QualType T1,
3252 Qualifiers T1Quals,
3253 QualType cv2T2, QualType T2,
3254 Qualifiers T2Quals,
3255 InitializationSequence &Sequence) {
3256 QualType DestType = Entity.getType();
3257 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003258 // Compute some basic properties of the types and the initializer.
3259 bool isLValueRef = DestType->isLValueReferenceType();
3260 bool isRValueRef = !isLValueRef;
3261 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003262 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003263 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003264 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003265 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003266 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003267 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003268
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003270 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003271 // "cv2 T2" as follows:
3272 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003274 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003275 // Note the analogous bullet points for rvlaue refs to functions. Because
3276 // there are no function rvalues in C++, rvalue refs to functions are treated
3277 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003278 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003279 bool T1Function = T1->isFunctionType();
3280 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003281 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003282 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003284 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003285 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003286 // reference-compatible with "cv2 T2," or
3287 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003289 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003290 // can occur. However, we do pay attention to whether it is a bit-field
3291 // to decide whether we're actually binding to a temporary created from
3292 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003293 if (DerivedToBase)
3294 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003295 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003296 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003297 else if (ObjCConversion)
3298 Sequence.AddObjCObjectConversionStep(
3299 S.Context.getQualifiedType(T1, T2Quals));
3300
Chandler Carruth5535c382010-01-12 20:32:25 +00003301 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003302 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003303 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003304 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003305 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003306 return;
3307 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003308
3309 // - has a class type (i.e., T2 is a class type), where T1 is not
3310 // reference-related to T2, and can be implicitly converted to an
3311 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3312 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003313 // applicable conversion functions (13.3.1.6) and choosing the best
3314 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003315 // If we have an rvalue ref to function type here, the rhs must be
3316 // an rvalue.
3317 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3318 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003319 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003320 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003321 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003322 Sequence);
3323 if (ConvOvlResult == OR_Success)
3324 return;
John McCall1d318332010-01-12 00:44:57 +00003325 if (ConvOvlResult != OR_No_Viable_Function) {
3326 Sequence.SetOverloadFailure(
3327 InitializationSequence::FK_ReferenceInitOverloadFailed,
3328 ConvOvlResult);
3329 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003330 }
3331 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003332
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003334 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003335 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003336 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003337 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3338 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3339 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003340 Sequence.SetOverloadFailure(
3341 InitializationSequence::FK_ReferenceInitOverloadFailed,
3342 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003343 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003344 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003345 ? (RefRelationship == Sema::Ref_Related
3346 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3347 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3348 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003349
Douglas Gregor20093b42009-12-09 23:02:17 +00003350 return;
3351 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003352
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003353 // - If the initializer expression
3354 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3355 // "cv1 T1" is reference-compatible with "cv2 T2"
3356 // Note: functions are handled below.
3357 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003358 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003359 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003360 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003361 (InitCategory.isXValue() ||
3362 (InitCategory.isPRValue() && T2->isRecordType()) ||
3363 (InitCategory.isPRValue() && T2->isArrayType()))) {
3364 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3365 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003366 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3367 // compiler the freedom to perform a copy here or bind to the
3368 // object, while C++0x requires that we bind directly to the
3369 // object. Hence, we always bind to the object without making an
3370 // extra copy. However, in C++03 requires that we check for the
3371 // presence of a suitable copy constructor:
3372 //
3373 // The constructor that would be used to make the copy shall
3374 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003375 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003376 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith83da2e72011-10-19 16:55:56 +00003377 else if (S.getLangOptions().CPlusPlus0x)
3378 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003381 if (DerivedToBase)
3382 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3383 ValueKind);
3384 else if (ObjCConversion)
3385 Sequence.AddObjCObjectConversionStep(
3386 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003387
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003388 if (T1Quals != T2Quals)
3389 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003391 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394
3395 // - has a class type (i.e., T2 is a class type), where T1 is not
3396 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003397 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3398 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003399 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003400 if (RefRelationship == Sema::Ref_Incompatible) {
3401 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3402 Kind, Initializer,
3403 /*AllowRValues=*/true,
3404 Sequence);
3405 if (ConvOvlResult)
3406 Sequence.SetOverloadFailure(
3407 InitializationSequence::FK_ReferenceInitOverloadFailed,
3408 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003409
Douglas Gregor20093b42009-12-09 23:02:17 +00003410 return;
3411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003412
Douglas Gregor20093b42009-12-09 23:02:17 +00003413 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3414 return;
3415 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003416
3417 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003418 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003419 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003420 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003421
Douglas Gregor20093b42009-12-09 23:02:17 +00003422 // Determine whether we are allowed to call explicit constructors or
3423 // explicit conversion operators.
3424 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003425
3426 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3427
John McCallf85e1932011-06-15 23:02:42 +00003428 ImplicitConversionSequence ICS
3429 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003430 /*SuppressUserConversions*/ false,
3431 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003432 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003433 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3434 /*AllowObjCWritebackConversion=*/false);
3435
3436 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003437 // FIXME: Use the conversion function set stored in ICS to turn
3438 // this into an overloading ambiguity diagnostic. However, we need
3439 // to keep that set as an OverloadCandidateSet rather than as some
3440 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003441 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3442 Sequence.SetOverloadFailure(
3443 InitializationSequence::FK_ReferenceInitOverloadFailed,
3444 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003445 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3446 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003447 else
3448 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003449 return;
John McCallf85e1932011-06-15 23:02:42 +00003450 } else {
3451 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003452 }
3453
3454 // [...] If T1 is reference-related to T2, cv1 must be the
3455 // same cv-qualification as, or greater cv-qualification
3456 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003457 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3458 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003460 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003461 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3462 return;
3463 }
3464
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003465 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003466 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003468 InitCategory.isLValue()) {
3469 Sequence.SetFailed(
3470 InitializationSequence::FK_RValueReferenceBindingToLValue);
3471 return;
3472 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003473
Douglas Gregor20093b42009-12-09 23:02:17 +00003474 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3475 return;
3476}
3477
3478/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479/// (C++ [dcl.init.string], C99 6.7.8).
3480static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003481 const InitializedEntity &Entity,
3482 const InitializationKind &Kind,
3483 Expr *Initializer,
3484 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003485 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003486}
3487
Douglas Gregor71d17402009-12-15 00:01:57 +00003488/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003490 const InitializedEntity &Entity,
3491 const InitializationKind &Kind,
3492 InitializationSequence &Sequence) {
3493 // C++ [dcl.init]p5:
3494 //
3495 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003496 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003497
Douglas Gregor71d17402009-12-15 00:01:57 +00003498 // -- if T is an array type, then each element is value-initialized;
3499 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3500 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003501
Douglas Gregor71d17402009-12-15 00:01:57 +00003502 if (const RecordType *RT = T->getAs<RecordType>()) {
3503 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3504 // -- if T is a class type (clause 9) with a user-declared
3505 // constructor (12.1), then the default constructor for T is
3506 // called (and the initialization is ill-formed if T has no
3507 // accessible default constructor);
3508 //
3509 // FIXME: we really want to refer to a single subobject of the array,
3510 // but Entity doesn't have a way to capture that (yet).
3511 if (ClassDecl->hasUserDeclaredConstructor())
3512 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513
Douglas Gregor16006c92009-12-16 18:50:27 +00003514 // -- if T is a (possibly cv-qualified) non-union class type
3515 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003516 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003517 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003518 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003519 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003520 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003522 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003523 }
3524 }
3525
Douglas Gregord6542d82009-12-22 15:35:07 +00003526 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003527}
3528
Douglas Gregor99a2e602009-12-16 01:38:02 +00003529/// \brief Attempt default initialization (C++ [dcl.init]p6).
3530static void TryDefaultInitialization(Sema &S,
3531 const InitializedEntity &Entity,
3532 const InitializationKind &Kind,
3533 InitializationSequence &Sequence) {
3534 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003535
Douglas Gregor99a2e602009-12-16 01:38:02 +00003536 // C++ [dcl.init]p6:
3537 // To default-initialize an object of type T means:
3538 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003539 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3540
Douglas Gregor99a2e602009-12-16 01:38:02 +00003541 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3542 // constructor for T is called (and the initialization is ill-formed if
3543 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003544 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003545 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3546 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003547 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003548
Douglas Gregor99a2e602009-12-16 01:38:02 +00003549 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550
Douglas Gregor99a2e602009-12-16 01:38:02 +00003551 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003552 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003553 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003554 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003555 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003556 return;
3557 }
3558
3559 // If the destination type has a lifetime property, zero-initialize it.
3560 if (DestType.getQualifiers().hasObjCLifetime()) {
3561 Sequence.AddZeroInitializationStep(Entity.getType());
3562 return;
3563 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003564}
3565
Douglas Gregor20093b42009-12-09 23:02:17 +00003566/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3567/// which enumerates all conversion functions and performs overload resolution
3568/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003570 const InitializedEntity &Entity,
3571 const InitializationKind &Kind,
3572 Expr *Initializer,
3573 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003574 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003575 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3576 QualType SourceType = Initializer->getType();
3577 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3578 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003579
Douglas Gregor4a520a22009-12-14 17:27:33 +00003580 // Build the candidate set directly in the initialization sequence
3581 // structure, so that it will persist if we fail.
3582 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3583 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003584
Douglas Gregor4a520a22009-12-14 17:27:33 +00003585 // Determine whether we are allowed to call explicit constructors or
3586 // explicit conversion operators.
3587 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
Douglas Gregor4a520a22009-12-14 17:27:33 +00003589 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3590 // The type we're converting to is a class type. Enumerate its constructors
3591 // to see if there is a suitable conversion.
3592 CXXRecordDecl *DestRecordDecl
3593 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003595 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003597 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003598 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003599 Con != ConEnd; ++Con) {
3600 NamedDecl *D = *Con;
3601 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003602
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003603 // Find the constructor (which may be a template).
3604 CXXConstructorDecl *Constructor = 0;
3605 FunctionTemplateDecl *ConstructorTmpl
3606 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003607 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003608 Constructor = cast<CXXConstructorDecl>(
3609 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003610 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003611 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003613 if (!Constructor->isInvalidDecl() &&
3614 Constructor->isConvertingConstructor(AllowExplicit)) {
3615 if (ConstructorTmpl)
3616 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3617 /*ExplicitArgs*/ 0,
3618 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003619 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003620 else
3621 S.AddOverloadCandidate(Constructor, FoundDecl,
3622 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003623 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003624 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003625 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003626 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003627 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003628
3629 SourceLocation DeclLoc = Initializer->getLocStart();
3630
Douglas Gregor4a520a22009-12-14 17:27:33 +00003631 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3632 // The type we're converting from is a class type, enumerate its conversion
3633 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003634
Eli Friedman33c2da92009-12-20 22:12:03 +00003635 // We can only enumerate the conversion functions for a complete type; if
3636 // the type isn't complete, simply skip this step.
3637 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3638 CXXRecordDecl *SourceRecordDecl
3639 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640
John McCalleec51cf2010-01-20 00:46:10 +00003641 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003642 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003643 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003644 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003645 I != E; ++I) {
3646 NamedDecl *D = *I;
3647 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3648 if (isa<UsingShadowDecl>(D))
3649 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003650
Eli Friedman33c2da92009-12-20 22:12:03 +00003651 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3652 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003653 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003654 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003655 else
John McCall32daa422010-03-31 01:36:47 +00003656 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003657
Eli Friedman33c2da92009-12-20 22:12:03 +00003658 if (AllowExplicit || !Conv->isExplicit()) {
3659 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003660 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003661 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003662 CandidateSet);
3663 else
John McCall9aa472c2010-03-19 07:35:19 +00003664 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003665 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003666 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003667 }
3668 }
3669 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670
3671 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003672 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003673 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003674 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003675 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003676 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003677 Result);
3678 return;
3679 }
John McCall1d318332010-01-12 00:44:57 +00003680
Douglas Gregor4a520a22009-12-14 17:27:33 +00003681 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003682 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003683 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684
Douglas Gregor4a520a22009-12-14 17:27:33 +00003685 if (isa<CXXConstructorDecl>(Function)) {
3686 // Add the user-defined conversion step. Any cv-qualification conversion is
3687 // subsumed by the initialization.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003688 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3689 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003690 return;
3691 }
3692
3693 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003694 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003695 if (ConvType->getAs<RecordType>()) {
3696 // If we're converting to a class type, there may be an copy if
3697 // the resulting temporary object (possible to create an object of
3698 // a base class type). That copy is not a separate conversion, so
3699 // we just make a note of the actual destination type (possibly a
3700 // base class of the type returned by the conversion function) and
3701 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003702 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3703 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003704 return;
3705 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003706
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003707 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3708 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003710 // If the conversion following the call to the conversion function
3711 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003712 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3713 Best->FinalConversion.Third) {
3714 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003715 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003716 ICS.Standard = Best->FinalConversion;
3717 Sequence.AddConversionSequenceStep(ICS, DestType);
3718 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003719}
3720
John McCallf85e1932011-06-15 23:02:42 +00003721/// The non-zero enum values here are indexes into diagnostic alternatives.
3722enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3723
3724/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003725static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3726 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003727 // Skip parens.
3728 e = e->IgnoreParens();
3729
3730 // Skip address-of nodes.
3731 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3732 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003733 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003734
3735 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003736 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3737 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003738 case CK_Dependent:
3739 case CK_BitCast:
3740 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003741 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003742 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003743
3744 case CK_ArrayToPointerDecay:
3745 return IIK_nonscalar;
3746
3747 case CK_NullToPointer:
3748 return IIK_okay;
3749
3750 default:
3751 break;
3752 }
3753
3754 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003755 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3756 if (!isAddressOf) return IIK_nonlocal;
3757
3758 VarDecl *var;
3759 if (isa<DeclRefExpr>(e)) {
3760 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3761 if (!var) return IIK_nonlocal;
3762 } else {
3763 var = cast<BlockDeclRefExpr>(e)->getDecl();
3764 }
3765
3766 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003767
3768 // If we have a conditional operator, check both sides.
3769 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003770 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003771 return iik;
3772
John McCallc03fa492011-06-27 23:59:58 +00003773 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003774
3775 // These are never scalar.
3776 } else if (isa<ArraySubscriptExpr>(e)) {
3777 return IIK_nonscalar;
3778
3779 // Otherwise, it needs to be a null pointer constant.
3780 } else {
3781 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3782 ? IIK_okay : IIK_nonlocal);
3783 }
3784
3785 return IIK_nonlocal;
3786}
3787
3788/// Check whether the given expression is a valid operand for an
3789/// indirect copy/restore.
3790static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3791 assert(src->isRValue());
3792
John McCallc03fa492011-06-27 23:59:58 +00003793 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003794 if (iik == IIK_okay) return;
3795
3796 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3797 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3798 << src->getSourceRange();
3799}
3800
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003801/// \brief Determine whether we have compatible array types for the
3802/// purposes of GNU by-copy array initialization.
3803static bool hasCompatibleArrayTypes(ASTContext &Context,
3804 const ArrayType *Dest,
3805 const ArrayType *Source) {
3806 // If the source and destination array types are equivalent, we're
3807 // done.
3808 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3809 return true;
3810
3811 // Make sure that the element types are the same.
3812 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3813 return false;
3814
3815 // The only mismatch we allow is when the destination is an
3816 // incomplete array type and the source is a constant array type.
3817 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3818}
3819
John McCallf85e1932011-06-15 23:02:42 +00003820static bool tryObjCWritebackConversion(Sema &S,
3821 InitializationSequence &Sequence,
3822 const InitializedEntity &Entity,
3823 Expr *Initializer) {
3824 bool ArrayDecay = false;
3825 QualType ArgType = Initializer->getType();
3826 QualType ArgPointee;
3827 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3828 ArrayDecay = true;
3829 ArgPointee = ArgArrayType->getElementType();
3830 ArgType = S.Context.getPointerType(ArgPointee);
3831 }
3832
3833 // Handle write-back conversion.
3834 QualType ConvertedArgType;
3835 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3836 ConvertedArgType))
3837 return false;
3838
3839 // We should copy unless we're passing to an argument explicitly
3840 // marked 'out'.
3841 bool ShouldCopy = true;
3842 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3843 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3844
3845 // Do we need an lvalue conversion?
3846 if (ArrayDecay || Initializer->isGLValue()) {
3847 ImplicitConversionSequence ICS;
3848 ICS.setStandard();
3849 ICS.Standard.setAsIdentityConversion();
3850
3851 QualType ResultType;
3852 if (ArrayDecay) {
3853 ICS.Standard.First = ICK_Array_To_Pointer;
3854 ResultType = S.Context.getPointerType(ArgPointee);
3855 } else {
3856 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3857 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3858 }
3859
3860 Sequence.AddConversionSequenceStep(ICS, ResultType);
3861 }
3862
3863 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3864 return true;
3865}
3866
Douglas Gregor20093b42009-12-09 23:02:17 +00003867InitializationSequence::InitializationSequence(Sema &S,
3868 const InitializedEntity &Entity,
3869 const InitializationKind &Kind,
3870 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003871 unsigned NumArgs)
3872 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003873 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003874
Douglas Gregor20093b42009-12-09 23:02:17 +00003875 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003876 // The semantics of initializers are as follows. The destination type is
3877 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003878 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003879 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003880 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003881 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003882
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003883 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003884 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3885 SequenceKind = DependentSequence;
3886 return;
3887 }
3888
Sebastian Redl7491c492011-06-05 13:59:11 +00003889 // Almost everything is a normal sequence.
3890 setSequenceKind(NormalSequence);
3891
John McCall241d5582010-12-07 22:54:16 +00003892 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00003893 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00003894 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00003895 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3896 if (result.isInvalid()) {
3897 SetFailed(FK_PlaceholderType);
3898 return;
John McCall5acb0c92011-10-17 18:40:02 +00003899 }
John McCall32509f12011-11-15 01:35:18 +00003900 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00003901 }
John McCall241d5582010-12-07 22:54:16 +00003902
John McCall5acb0c92011-10-17 18:40:02 +00003903
Douglas Gregor20093b42009-12-09 23:02:17 +00003904 QualType SourceType;
3905 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003906 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003907 Initializer = Args[0];
3908 if (!isa<InitListExpr>(Initializer))
3909 SourceType = Initializer->getType();
3910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
3912 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003913 // list-initialized (8.5.4).
3914 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003915 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003916 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003917 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003918
Douglas Gregor20093b42009-12-09 23:02:17 +00003919 // - If the destination type is a reference type, see 8.5.3.
3920 if (DestType->isReferenceType()) {
3921 // C++0x [dcl.init.ref]p1:
3922 // A variable declared to be a T& or T&&, that is, "reference to type T"
3923 // (8.3.2), shall be initialized by an object, or function, of type T or
3924 // by an object that can be converted into a T.
3925 // (Therefore, multiple arguments are not permitted.)
3926 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003927 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003928 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003929 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003930 return;
3931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003932
Douglas Gregor20093b42009-12-09 23:02:17 +00003933 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003934 if (Kind.getKind() == InitializationKind::IK_Value ||
3935 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003936 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003937 return;
3938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003939
Douglas Gregor99a2e602009-12-16 01:38:02 +00003940 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003941 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003942 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003943 return;
3944 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003945
John McCallce6c9b72011-02-21 07:22:22 +00003946 // - If the destination type is an array of characters, an array of
3947 // char16_t, an array of char32_t, or an array of wchar_t, and the
3948 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003949 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003950 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003951 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00003952 if (Initializer && isa<VariableArrayType>(DestAT)) {
3953 SetFailed(FK_VariableLengthArrayHasInitializer);
3954 return;
3955 }
3956
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003957 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003958 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003959 return;
3960 }
3961
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003962 // Note: as an GNU C extension, we allow initialization of an
3963 // array from a compound literal that creates an array of the same
3964 // type, so long as the initializer has no side effects.
3965 if (!S.getLangOptions().CPlusPlus && Initializer &&
3966 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3967 Initializer->getType()->isArrayType()) {
3968 const ArrayType *SourceAT
3969 = Context.getAsArrayType(Initializer->getType());
3970 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003971 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003972 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003973 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003974 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003975 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003976 }
3977 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003978 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003979 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003980 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981
Douglas Gregor20093b42009-12-09 23:02:17 +00003982 return;
3983 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003984
John McCallf85e1932011-06-15 23:02:42 +00003985 // Determine whether we should consider writeback conversions for
3986 // Objective-C ARC.
3987 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3988 Entity.getKind() == InitializedEntity::EK_Parameter;
3989
3990 // We're at the end of the line for C: it's either a write-back conversion
3991 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003992 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003993 // If allowed, check whether this is an Objective-C writeback conversion.
3994 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003995 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003996 return;
3997 }
3998
3999 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004000 AddCAssignmentStep(DestType);
4001 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004002 return;
4003 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004
John McCallf85e1932011-06-15 23:02:42 +00004005 assert(S.getLangOptions().CPlusPlus);
4006
Douglas Gregor20093b42009-12-09 23:02:17 +00004007 // - If the destination type is a (possibly cv-qualified) class type:
4008 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009 // - If the initialization is direct-initialization, or if it is
4010 // copy-initialization where the cv-unqualified version of the
4011 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004012 // class of the destination, constructors are considered. [...]
4013 if (Kind.getKind() == InitializationKind::IK_Direct ||
4014 (Kind.getKind() == InitializationKind::IK_Copy &&
4015 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4016 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004018 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004019 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004020 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004022 // used) to a derived class thereof are enumerated as described in
4023 // 13.3.1.4, and the best one is chosen through overload resolution
4024 // (13.3).
4025 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004026 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004027 return;
4028 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004029
Douglas Gregor99a2e602009-12-16 01:38:02 +00004030 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004031 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004032 return;
4033 }
4034 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004035
4036 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004037 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004038 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004039 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4040 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004041 return;
4042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043
Douglas Gregor20093b42009-12-09 23:02:17 +00004044 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004045 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004046 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004047 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004048 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004049
4050 ImplicitConversionSequence ICS
4051 = S.TryImplicitConversion(Initializer, Entity.getType(),
4052 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004053 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004054 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004055 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4056 allowObjCWritebackConversion);
4057
4058 if (ICS.isStandard() &&
4059 ICS.Standard.Second == ICK_Writeback_Conversion) {
4060 // Objective-C ARC writeback conversion.
4061
4062 // We should copy unless we're passing to an argument explicitly
4063 // marked 'out'.
4064 bool ShouldCopy = true;
4065 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4066 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4067
4068 // If there was an lvalue adjustment, add it as a separate conversion.
4069 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4070 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4071 ImplicitConversionSequence LvalueICS;
4072 LvalueICS.setStandard();
4073 LvalueICS.Standard.setAsIdentityConversion();
4074 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4075 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004076 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004077 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004078
4079 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004080 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004081 DeclAccessPair dap;
4082 if (Initializer->getType() == Context.OverloadTy &&
4083 !S.ResolveAddressOfOverloadedFunction(Initializer
4084 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004085 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004086 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004087 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004088 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004089 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004090
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004091 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004092 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004093}
4094
4095InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004096 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004097 StepEnd = Steps.end();
4098 Step != StepEnd; ++Step)
4099 Step->Destroy();
4100}
4101
4102//===----------------------------------------------------------------------===//
4103// Perform initialization
4104//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004106getAssignmentAction(const InitializedEntity &Entity) {
4107 switch(Entity.getKind()) {
4108 case InitializedEntity::EK_Variable:
4109 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004110 case InitializedEntity::EK_Exception:
4111 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004112 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004113 return Sema::AA_Initializing;
4114
4115 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004117 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4118 return Sema::AA_Sending;
4119
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004120 return Sema::AA_Passing;
4121
4122 case InitializedEntity::EK_Result:
4123 return Sema::AA_Returning;
4124
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004125 case InitializedEntity::EK_Temporary:
4126 // FIXME: Can we tell apart casting vs. converting?
4127 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004128
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004129 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004130 case InitializedEntity::EK_ArrayElement:
4131 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004132 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004133 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004134 return Sema::AA_Initializing;
4135 }
4136
David Blaikie7530c032012-01-17 06:56:22 +00004137 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004138}
4139
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004140/// \brief Whether we should binding a created object as a temporary when
4141/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004142static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004143 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004144 case InitializedEntity::EK_ArrayElement:
4145 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004146 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004147 case InitializedEntity::EK_New:
4148 case InitializedEntity::EK_Variable:
4149 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004150 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004151 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004152 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004153 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004154 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004155 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004156
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004157 case InitializedEntity::EK_Parameter:
4158 case InitializedEntity::EK_Temporary:
4159 return true;
4160 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004161
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004162 llvm_unreachable("missed an InitializedEntity kind?");
4163}
4164
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004165/// \brief Whether the given entity, when initialized with an object
4166/// created for that initialization, requires destruction.
4167static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4168 switch (Entity.getKind()) {
4169 case InitializedEntity::EK_Member:
4170 case InitializedEntity::EK_Result:
4171 case InitializedEntity::EK_New:
4172 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004173 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004174 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004175 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004176 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004177 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004179 case InitializedEntity::EK_Variable:
4180 case InitializedEntity::EK_Parameter:
4181 case InitializedEntity::EK_Temporary:
4182 case InitializedEntity::EK_ArrayElement:
4183 case InitializedEntity::EK_Exception:
4184 return true;
4185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004186
4187 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004188}
4189
Richard Smith83da2e72011-10-19 16:55:56 +00004190/// \brief Look for copy and move constructors and constructor templates, for
4191/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4192static void LookupCopyAndMoveConstructors(Sema &S,
4193 OverloadCandidateSet &CandidateSet,
4194 CXXRecordDecl *Class,
4195 Expr *CurInitExpr) {
4196 DeclContext::lookup_iterator Con, ConEnd;
4197 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4198 Con != ConEnd; ++Con) {
4199 CXXConstructorDecl *Constructor = 0;
4200
4201 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4202 // Handle copy/moveconstructors, only.
4203 if (!Constructor || Constructor->isInvalidDecl() ||
4204 !Constructor->isCopyOrMoveConstructor() ||
4205 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4206 continue;
4207
4208 DeclAccessPair FoundDecl
4209 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4210 S.AddOverloadCandidate(Constructor, FoundDecl,
4211 &CurInitExpr, 1, CandidateSet);
4212 continue;
4213 }
4214
4215 // Handle constructor templates.
4216 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4217 if (ConstructorTmpl->isInvalidDecl())
4218 continue;
4219
4220 Constructor = cast<CXXConstructorDecl>(
4221 ConstructorTmpl->getTemplatedDecl());
4222 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4223 continue;
4224
4225 // FIXME: Do we need to limit this to copy-constructor-like
4226 // candidates?
4227 DeclAccessPair FoundDecl
4228 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4229 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4230 &CurInitExpr, 1, CandidateSet, true);
4231 }
4232}
4233
4234/// \brief Get the location at which initialization diagnostics should appear.
4235static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4236 Expr *Initializer) {
4237 switch (Entity.getKind()) {
4238 case InitializedEntity::EK_Result:
4239 return Entity.getReturnLoc();
4240
4241 case InitializedEntity::EK_Exception:
4242 return Entity.getThrowLoc();
4243
4244 case InitializedEntity::EK_Variable:
4245 return Entity.getDecl()->getLocation();
4246
4247 case InitializedEntity::EK_ArrayElement:
4248 case InitializedEntity::EK_Member:
4249 case InitializedEntity::EK_Parameter:
4250 case InitializedEntity::EK_Temporary:
4251 case InitializedEntity::EK_New:
4252 case InitializedEntity::EK_Base:
4253 case InitializedEntity::EK_Delegating:
4254 case InitializedEntity::EK_VectorElement:
4255 case InitializedEntity::EK_ComplexElement:
4256 case InitializedEntity::EK_BlockElement:
4257 return Initializer->getLocStart();
4258 }
4259 llvm_unreachable("missed an InitializedEntity kind?");
4260}
4261
Douglas Gregor523d46a2010-04-18 07:40:54 +00004262/// \brief Make a (potentially elidable) temporary copy of the object
4263/// provided by the given initializer by calling the appropriate copy
4264/// constructor.
4265///
4266/// \param S The Sema object used for type-checking.
4267///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004268/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004269/// the type of the initializer expression or a superclass thereof.
4270///
4271/// \param Enter The entity being initialized.
4272///
4273/// \param CurInit The initializer expression.
4274///
4275/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4276/// is permitted in C++03 (but not C++0x) when binding a reference to
4277/// an rvalue.
4278///
4279/// \returns An expression that copies the initializer expression into
4280/// a temporary object, or an error expression if a copy could not be
4281/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004282static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004283 QualType T,
4284 const InitializedEntity &Entity,
4285 ExprResult CurInit,
4286 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004287 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004288 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004290 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004291 Class = cast<CXXRecordDecl>(Record->getDecl());
4292 if (!Class)
4293 return move(CurInit);
4294
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004295 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004296 // When certain criteria are met, an implementation is allowed to
4297 // omit the copy/move construction of a class object, even if the
4298 // copy/move constructor and/or destructor for the object have
4299 // side effects. [...]
4300 // - when a temporary class object that has not been bound to a
4301 // reference (12.2) would be copied/moved to a class object
4302 // with the same cv-unqualified type, the copy/move operation
4303 // can be omitted by constructing the temporary object
4304 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004306 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004307 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004309 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004310 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004311 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004312
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004314 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4315 return move(CurInit);
4316
Douglas Gregorcc15f012011-01-21 19:38:21 +00004317 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004318 // Only consider constructors and constructor templates. Per
4319 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4320 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004321 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004322 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004324 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4325
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004326 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004327 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004328 case OR_Success:
4329 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004330
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004331 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004332 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4333 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4334 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004335 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004336 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004337 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004338 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004339 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004340 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004341
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004342 case OR_Ambiguous:
4343 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004344 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004345 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004346 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004347 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004348
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004349 case OR_Deleted:
4350 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004351 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004352 << CurInitExpr->getSourceRange();
4353 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004354 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004355 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004356 }
4357
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004358 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004359 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004360 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004361
Anders Carlsson9a68a672010-04-21 18:47:17 +00004362 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004363 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004364
4365 if (IsExtraneousCopy) {
4366 // If this is a totally extraneous copy for C++03 reference
4367 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004368 // expression. We don't generate an (elided) copy operation here
4369 // because doing so would require us to pass down a flag to avoid
4370 // infinite recursion, where each step adds another extraneous,
4371 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004372
Douglas Gregor2559a702010-04-18 07:57:34 +00004373 // Instantiate the default arguments of any extra parameters in
4374 // the selected copy constructor, as if we were going to create a
4375 // proper call to the copy constructor.
4376 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4377 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4378 if (S.RequireCompleteType(Loc, Parm->getType(),
4379 S.PDiag(diag::err_call_incomplete_argument)))
4380 break;
4381
4382 // Build the default argument expression; we don't actually care
4383 // if this succeeds or not, because this routine will complain
4384 // if there was a problem.
4385 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4386 }
4387
Douglas Gregor523d46a2010-04-18 07:40:54 +00004388 return S.Owned(CurInitExpr);
4389 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004390
Chandler Carruth25ca4212011-02-25 19:41:05 +00004391 S.MarkDeclarationReferenced(Loc, Constructor);
4392
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004393 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004394 // constructor call (we might have derived-to-base conversions, or
4395 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004396 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004397 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004398 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004399
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004400 // Actually perform the constructor call.
4401 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004402 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004403 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004404 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004405 CXXConstructExpr::CK_Complete,
4406 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004408 // If we're supposed to bind temporaries, do so.
4409 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4410 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4411 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004412}
Douglas Gregor20093b42009-12-09 23:02:17 +00004413
Richard Smith83da2e72011-10-19 16:55:56 +00004414/// \brief Check whether elidable copy construction for binding a reference to
4415/// a temporary would have succeeded if we were building in C++98 mode, for
4416/// -Wc++98-compat.
4417static void CheckCXX98CompatAccessibleCopy(Sema &S,
4418 const InitializedEntity &Entity,
4419 Expr *CurInitExpr) {
4420 assert(S.getLangOptions().CPlusPlus0x);
4421
4422 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4423 if (!Record)
4424 return;
4425
4426 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4427 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4428 == DiagnosticsEngine::Ignored)
4429 return;
4430
4431 // Find constructors which would have been considered.
4432 OverloadCandidateSet CandidateSet(Loc);
4433 LookupCopyAndMoveConstructors(
4434 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4435
4436 // Perform overload resolution.
4437 OverloadCandidateSet::iterator Best;
4438 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4439
4440 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4441 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4442 << CurInitExpr->getSourceRange();
4443
4444 switch (OR) {
4445 case OR_Success:
4446 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4447 Best->FoundDecl.getAccess(), Diag);
4448 // FIXME: Check default arguments as far as that's possible.
4449 break;
4450
4451 case OR_No_Viable_Function:
4452 S.Diag(Loc, Diag);
4453 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4454 break;
4455
4456 case OR_Ambiguous:
4457 S.Diag(Loc, Diag);
4458 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4459 break;
4460
4461 case OR_Deleted:
4462 S.Diag(Loc, Diag);
4463 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4464 << 1 << Best->Function->isDeleted();
4465 break;
4466 }
4467}
4468
Douglas Gregora41a8c52010-04-22 00:20:18 +00004469void InitializationSequence::PrintInitLocationNote(Sema &S,
4470 const InitializedEntity &Entity) {
4471 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4472 if (Entity.getDecl()->getLocation().isInvalid())
4473 return;
4474
4475 if (Entity.getDecl()->getDeclName())
4476 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4477 << Entity.getDecl()->getDeclName();
4478 else
4479 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4480 }
4481}
4482
Sebastian Redl3b802322011-07-14 19:07:55 +00004483static bool isReferenceBinding(const InitializationSequence::Step &s) {
4484 return s.Kind == InitializationSequence::SK_BindReference ||
4485 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4486}
4487
Sebastian Redl10f04a62011-12-22 14:44:04 +00004488static ExprResult
4489PerformConstructorInitialization(Sema &S,
4490 const InitializedEntity &Entity,
4491 const InitializationKind &Kind,
4492 MultiExprArg Args,
4493 const InitializationSequence::Step& Step,
4494 bool &ConstructorInitRequiresZeroInit) {
4495 unsigned NumArgs = Args.size();
4496 CXXConstructorDecl *Constructor
4497 = cast<CXXConstructorDecl>(Step.Function.Function);
4498 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4499
4500 // Build a call to the selected constructor.
4501 ASTOwningVector<Expr*> ConstructorArgs(S);
4502 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4503 ? Kind.getEqualLoc()
4504 : Kind.getLocation();
4505
4506 if (Kind.getKind() == InitializationKind::IK_Default) {
4507 // Force even a trivial, implicit default constructor to be
4508 // semantically checked. We do this explicitly because we don't build
4509 // the definition for completely trivial constructors.
4510 CXXRecordDecl *ClassDecl = Constructor->getParent();
4511 assert(ClassDecl && "No parent class for constructor.");
4512 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4513 ClassDecl->hasTrivialDefaultConstructor() &&
4514 !Constructor->isUsed(false))
4515 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4516 }
4517
4518 ExprResult CurInit = S.Owned((Expr *)0);
4519
4520 // Determine the arguments required to actually perform the constructor
4521 // call.
4522 if (S.CompleteConstructorCall(Constructor, move(Args),
4523 Loc, ConstructorArgs))
4524 return ExprError();
4525
4526
4527 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4528 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4529 (Kind.getKind() == InitializationKind::IK_Direct ||
4530 Kind.getKind() == InitializationKind::IK_Value)) {
4531 // An explicitly-constructed temporary, e.g., X(1, 2).
4532 unsigned NumExprs = ConstructorArgs.size();
4533 Expr **Exprs = (Expr **)ConstructorArgs.take();
4534 S.MarkDeclarationReferenced(Loc, Constructor);
4535 S.DiagnoseUseOfDecl(Constructor, Loc);
4536
4537 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4538 if (!TSInfo)
4539 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4540
4541 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4542 Constructor,
4543 TSInfo,
4544 Exprs,
4545 NumExprs,
4546 Kind.getParenRange(),
4547 HadMultipleCandidates,
4548 ConstructorInitRequiresZeroInit));
4549 } else {
4550 CXXConstructExpr::ConstructionKind ConstructKind =
4551 CXXConstructExpr::CK_Complete;
4552
4553 if (Entity.getKind() == InitializedEntity::EK_Base) {
4554 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4555 CXXConstructExpr::CK_VirtualBase :
4556 CXXConstructExpr::CK_NonVirtualBase;
4557 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4558 ConstructKind = CXXConstructExpr::CK_Delegating;
4559 }
4560
4561 // Only get the parenthesis range if it is a direct construction.
4562 SourceRange parenRange =
4563 Kind.getKind() == InitializationKind::IK_Direct ?
4564 Kind.getParenRange() : SourceRange();
4565
4566 // If the entity allows NRVO, mark the construction as elidable
4567 // unconditionally.
4568 if (Entity.allowsNRVO())
4569 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4570 Constructor, /*Elidable=*/true,
4571 move_arg(ConstructorArgs),
4572 HadMultipleCandidates,
4573 ConstructorInitRequiresZeroInit,
4574 ConstructKind,
4575 parenRange);
4576 else
4577 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4578 Constructor,
4579 move_arg(ConstructorArgs),
4580 HadMultipleCandidates,
4581 ConstructorInitRequiresZeroInit,
4582 ConstructKind,
4583 parenRange);
4584 }
4585 if (CurInit.isInvalid())
4586 return ExprError();
4587
4588 // Only check access if all of that succeeded.
4589 S.CheckConstructorAccess(Loc, Constructor, Entity,
4590 Step.Function.FoundDecl.getAccess());
4591 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4592
4593 if (shouldBindAsTemporary(Entity))
4594 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4595
4596 return move(CurInit);
4597}
4598
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004599ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004600InitializationSequence::Perform(Sema &S,
4601 const InitializedEntity &Entity,
4602 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004603 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004604 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004605 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004606 unsigned NumArgs = Args.size();
4607 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004608 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004609 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004610
Sebastian Redl7491c492011-06-05 13:59:11 +00004611 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004612 // If the declaration is a non-dependent, incomplete array type
4613 // that has an initializer, then its type will be completed once
4614 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004615 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004616 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004617 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004618 if (const IncompleteArrayType *ArrayT
4619 = S.Context.getAsIncompleteArrayType(DeclType)) {
4620 // FIXME: We don't currently have the ability to accurately
4621 // compute the length of an initializer list without
4622 // performing full type-checking of the initializer list
4623 // (since we have to determine where braces are implicitly
4624 // introduced and such). So, we fall back to making the array
4625 // type a dependently-sized array type with no specified
4626 // bound.
4627 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4628 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004629
Douglas Gregord87b61f2009-12-10 17:56:55 +00004630 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004631 if (DeclaratorDecl *DD = Entity.getDecl()) {
4632 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4633 TypeLoc TL = TInfo->getTypeLoc();
4634 if (IncompleteArrayTypeLoc *ArrayLoc
4635 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4636 Brackets = ArrayLoc->getBracketsRange();
4637 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004638 }
4639
4640 *ResultType
4641 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4642 /*NumElts=*/0,
4643 ArrayT->getSizeModifier(),
4644 ArrayT->getIndexTypeCVRQualifiers(),
4645 Brackets);
4646 }
4647
4648 }
4649 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004650 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4651 Kind.isExplicitCast());
4652 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004653 }
4654
Sebastian Redl7491c492011-06-05 13:59:11 +00004655 // No steps means no initialization.
4656 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004657 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658
Douglas Gregord6542d82009-12-22 15:35:07 +00004659 QualType DestType = Entity.getType().getNonReferenceType();
4660 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004661 // the same as Entity.getDecl()->getType() in cases involving type merging,
4662 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004663 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004664 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004665 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004666
John McCall60d7b3a2010-08-24 06:29:42 +00004667 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004668
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004669 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004670 // grab the only argument out the Args and place it into the "current"
4671 // initializer.
4672 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004673 case SK_ResolveAddressOfOverloadedFunction:
4674 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004675 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004676 case SK_CastDerivedToBaseLValue:
4677 case SK_BindReference:
4678 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004679 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004680 case SK_UserConversion:
4681 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004682 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004683 case SK_QualificationConversionRValue:
4684 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004685 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004686 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004687 case SK_UnwrapInitList:
4688 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004689 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004690 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004691 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004692 case SK_ArrayInit:
4693 case SK_PassByIndirectCopyRestore:
4694 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00004695 case SK_ProduceObjCObject:
4696 case SK_StdInitializerList: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004697 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004698 CurInit = Args.get()[0];
4699 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004700 break;
John McCallf6a16482010-12-04 03:47:34 +00004701 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004702
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004703 case SK_ConstructorInitialization:
4704 case SK_ZeroInitialization:
4705 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004706 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004707
4708 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004709 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004710 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004711 for (step_iterator Step = step_begin(), StepEnd = step_end();
4712 Step != StepEnd; ++Step) {
4713 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004714 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004715
John Wiegley429bb272011-04-08 18:41:53 +00004716 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717
Douglas Gregor20093b42009-12-09 23:02:17 +00004718 switch (Step->Kind) {
4719 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004721 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004722 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004723 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004724 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004725 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004726 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004727 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728
Douglas Gregor20093b42009-12-09 23:02:17 +00004729 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004730 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004731 case SK_CastDerivedToBaseLValue: {
4732 // We have a derived-to-base cast that produces either an rvalue or an
4733 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004734
John McCallf871d0c2010-08-07 06:22:56 +00004735 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004736
Douglas Gregor20093b42009-12-09 23:02:17 +00004737 // Casts to inaccessible base classes are allowed with C-style casts.
4738 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4739 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004740 CurInit.get()->getLocStart(),
4741 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004742 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004743 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004744
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004745 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4746 QualType T = SourceType;
4747 if (const PointerType *Pointer = T->getAs<PointerType>())
4748 T = Pointer->getPointeeType();
4749 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004750 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004751 cast<CXXRecordDecl>(RecordTy->getDecl()));
4752 }
4753
John McCall5baba9d2010-08-25 10:28:54 +00004754 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004755 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004756 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004757 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004758 VK_XValue :
4759 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004760 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4761 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004762 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004763 CurInit.get(),
4764 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004765 break;
4766 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004767
Douglas Gregor20093b42009-12-09 23:02:17 +00004768 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004769 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004770 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4771 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004772 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004773 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004774 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004775 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004776 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004777 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004778
John Wiegley429bb272011-04-08 18:41:53 +00004779 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004780 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004781 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4782 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004783 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004784 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004785 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004787
Douglas Gregor20093b42009-12-09 23:02:17 +00004788 // Reference binding does not have any corresponding ASTs.
4789
4790 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004791 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004792 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004793
Douglas Gregor20093b42009-12-09 23:02:17 +00004794 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004795
Douglas Gregor20093b42009-12-09 23:02:17 +00004796 case SK_BindReferenceToTemporary:
4797 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004798 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004799 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004800
Douglas Gregor03e80032011-06-21 17:03:29 +00004801 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004802 CurInit = new (S.Context) MaterializeTemporaryExpr(
4803 Entity.getType().getNonReferenceType(),
4804 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004805 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004806
4807 // If we're binding to an Objective-C object that has lifetime, we
4808 // need cleanups.
4809 if (S.getLangOptions().ObjCAutoRefCount &&
4810 CurInit.get()->getType()->isObjCLifetimeType())
4811 S.ExprNeedsCleanups = true;
4812
Douglas Gregor20093b42009-12-09 23:02:17 +00004813 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004814
Douglas Gregor523d46a2010-04-18 07:40:54 +00004815 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004816 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004817 /*IsExtraneousCopy=*/true);
4818 break;
4819
Douglas Gregor20093b42009-12-09 23:02:17 +00004820 case SK_UserConversion: {
4821 // We have a user-defined conversion that invokes either a constructor
4822 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004823 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004824 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004825 FunctionDecl *Fn = Step->Function.Function;
4826 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004827 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004828 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004829 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004830 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004831 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004832 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004833 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004834
Douglas Gregor20093b42009-12-09 23:02:17 +00004835 // Determine the arguments required to actually perform the constructor
4836 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004837 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004838 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004839 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004840 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004841 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004842
Douglas Gregor20093b42009-12-09 23:02:17 +00004843 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004844 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004845 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004846 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004847 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004848 CXXConstructExpr::CK_Complete,
4849 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004850 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004851 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004852
Anders Carlsson9a68a672010-04-21 18:47:17 +00004853 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004854 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004855 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004856
John McCall2de56d12010-08-25 11:45:40 +00004857 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004858 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4859 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4860 S.IsDerivedFrom(SourceType, Class))
4861 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004862
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004863 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004864 } else {
4865 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004866 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00004867 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004868 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004869 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004870
4871 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004872 // derived-to-base conversion? I believe the answer is "no", because
4873 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004874 ExprResult CurInitExprRes =
4875 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4876 FoundFn, Conversion);
4877 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004878 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004879 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004880
Douglas Gregor20093b42009-12-09 23:02:17 +00004881 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004882 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4883 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00004884 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004885 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004886
John McCall2de56d12010-08-25 11:45:40 +00004887 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004888
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004889 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004890 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004891
Sebastian Redl3b802322011-07-14 19:07:55 +00004892 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00004893 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4894
4895 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004896 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004897 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004898 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004899 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004900 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004901 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004902 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4903 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004904 }
4905 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004906
John McCallf871d0c2010-08-07 06:22:56 +00004907 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004908 CurInit.get()->getType(),
4909 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00004910 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00004911 if (MaybeBindToTemp)
4912 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00004913 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004914 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4915 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00004916 break;
4917 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004918
Douglas Gregor20093b42009-12-09 23:02:17 +00004919 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004920 case SK_QualificationConversionXValue:
4921 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004922 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004923 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004924 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004925 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004926 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004927 VK_XValue :
4928 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004929 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004930 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004931 }
4932
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004933 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004934 Sema::CheckedConversionKind CCK
4935 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4936 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00004937 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00004938 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004939 ExprResult CurInitExprRes =
4940 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004941 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004942 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004943 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004944 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004945 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004946 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004947
Douglas Gregord87b61f2009-12-10 17:56:55 +00004948 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004949 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004950 // Hack: We must pass *ResultType if available in order to set the type
4951 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
4952 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
4953 // temporary, not a reference, so we should pass Ty.
4954 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
4955 // Since this step is never used for a reference directly, we explicitly
4956 // unwrap references here and rewrap them afterwards.
4957 // We also need to create a InitializeTemporary entity for this.
4958 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
4959 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
4960 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
4961 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
4962 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redlc2235182011-10-16 18:19:28 +00004963 Kind.getKind() != InitializationKind::IK_Direct ||
4964 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00004965 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00004966 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004967
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004968 if (ResultType) {
4969 if ((*ResultType)->isRValueReferenceType())
4970 Ty = S.Context.getRValueReferenceType(Ty);
4971 else if ((*ResultType)->isLValueReferenceType())
4972 Ty = S.Context.getLValueReferenceType(Ty,
4973 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
4974 *ResultType = Ty;
4975 }
4976
4977 InitListExpr *StructuredInitList =
4978 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004979 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004980 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004981 break;
4982 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004983
Sebastian Redl10f04a62011-12-22 14:44:04 +00004984 case SK_ListConstructorCall: {
4985 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
4986 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
4987 CurInit = PerformConstructorInitialization(S, Entity, Kind,
4988 move(Arg), *Step,
4989 ConstructorInitRequiresZeroInit);
4990 break;
4991 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004992
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004993 case SK_UnwrapInitList:
4994 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
4995 break;
4996
4997 case SK_RewrapInitList: {
4998 Expr *E = CurInit.take();
4999 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5000 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5001 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5002 ILE->setSyntacticForm(Syntactic);
5003 ILE->setType(E->getType());
5004 ILE->setValueKind(E->getValueKind());
5005 CurInit = S.Owned(ILE);
5006 break;
5007 }
5008
Sebastian Redl10f04a62011-12-22 14:44:04 +00005009 case SK_ConstructorInitialization:
5010 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5011 *Step,
5012 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005013 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005014
Douglas Gregor71d17402009-12-15 00:01:57 +00005015 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005016 step_iterator NextStep = Step;
5017 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005018 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005019 NextStep->Kind == SK_ConstructorInitialization) {
5020 // The need for zero-initialization is recorded directly into
5021 // the call to the object's constructor within the next step.
5022 ConstructorInitRequiresZeroInit = true;
5023 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5024 S.getLangOptions().CPlusPlus &&
5025 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005026 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5027 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005028 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005029 Kind.getRange().getBegin());
5030
5031 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5032 TSInfo->getType().getNonLValueExprType(S.Context),
5033 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005034 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005035 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005036 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005037 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005038 break;
5039 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005040
5041 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005042 QualType SourceType = CurInit.get()->getType();
5043 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005044 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005045 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5046 if (Result.isInvalid())
5047 return ExprError();
5048 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00005049
5050 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005051 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00005052 if (ConvTy != Sema::Compatible &&
5053 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005054 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005055 == Sema::Compatible)
5056 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005057 if (CurInitExprRes.isInvalid())
5058 return ExprError();
5059 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00005060
Douglas Gregora41a8c52010-04-22 00:20:18 +00005061 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005062 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5063 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005064 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005065 getAssignmentAction(Entity),
5066 &Complained)) {
5067 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005068 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005069 } else if (Complained)
5070 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005071 break;
5072 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005073
5074 case SK_StringInit: {
5075 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005076 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005077 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005078 break;
5079 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005080
5081 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005082 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005083 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005084 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005085 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005086
5087 case SK_ArrayInit:
5088 // Okay: we checked everything before creating this step. Note that
5089 // this is a GNU extension.
5090 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005091 << Step->Type << CurInit.get()->getType()
5092 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005093
5094 // If the destination type is an incomplete array type, update the
5095 // type accordingly.
5096 if (ResultType) {
5097 if (const IncompleteArrayType *IncompleteDest
5098 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5099 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005100 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005101 *ResultType = S.Context.getConstantArrayType(
5102 IncompleteDest->getElementType(),
5103 ConstantSource->getSize(),
5104 ArrayType::Normal, 0);
5105 }
5106 }
5107 }
John McCallf85e1932011-06-15 23:02:42 +00005108 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005109
John McCallf85e1932011-06-15 23:02:42 +00005110 case SK_PassByIndirectCopyRestore:
5111 case SK_PassByIndirectRestore:
5112 checkIndirectCopyRestoreSource(S, CurInit.get());
5113 CurInit = S.Owned(new (S.Context)
5114 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5115 Step->Kind == SK_PassByIndirectCopyRestore));
5116 break;
5117
5118 case SK_ProduceObjCObject:
5119 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005120 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005121 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005122 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005123
5124 case SK_StdInitializerList: {
5125 QualType Dest = Step->Type;
5126 QualType E;
5127 bool Success = S.isStdInitializerList(Dest, &E);
5128 (void)Success;
5129 assert(Success && "Destination type changed?");
5130 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5131 unsigned NumInits = ILE->getNumInits();
5132 SmallVector<Expr*, 16> Converted(NumInits);
5133 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5134 S.Context.getConstantArrayType(E,
5135 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5136 NumInits),
5137 ArrayType::Normal, 0));
5138 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5139 0, HiddenArray);
5140 for (unsigned i = 0; i < NumInits; ++i) {
5141 Element.setElementIndex(i);
5142 ExprResult Init = S.Owned(ILE->getInit(i));
5143 ExprResult Res = S.PerformCopyInitialization(Element,
5144 Init.get()->getExprLoc(),
5145 Init);
5146 assert(!Res.isInvalid() && "Result changed since try phase.");
5147 Converted[i] = Res.take();
5148 }
5149 InitListExpr *Semantic = new (S.Context)
5150 InitListExpr(S.Context, ILE->getLBraceLoc(),
5151 Converted.data(), NumInits, ILE->getRBraceLoc());
5152 Semantic->setSyntacticForm(ILE);
5153 Semantic->setType(Dest);
5154 CurInit = S.Owned(Semantic);
5155 break;
5156 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005157 }
5158 }
John McCall15d7d122010-11-11 03:21:53 +00005159
5160 // Diagnose non-fatal problems with the completed initialization.
5161 if (Entity.getKind() == InitializedEntity::EK_Member &&
5162 cast<FieldDecl>(Entity.getDecl())->isBitField())
5163 S.CheckBitFieldInitialization(Kind.getLocation(),
5164 cast<FieldDecl>(Entity.getDecl()),
5165 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005166
Douglas Gregor20093b42009-12-09 23:02:17 +00005167 return move(CurInit);
5168}
5169
5170//===----------------------------------------------------------------------===//
5171// Diagnose initialization failures
5172//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005174 const InitializedEntity &Entity,
5175 const InitializationKind &Kind,
5176 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005177 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005178 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005179
Douglas Gregord6542d82009-12-22 15:35:07 +00005180 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005181 switch (Failure) {
5182 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005183 // FIXME: Customize for the initialized entity?
5184 if (NumArgs == 0)
5185 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5186 << DestType.getNonReferenceType();
5187 else // FIXME: diagnostic below could be better!
5188 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5189 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005190 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005191
Douglas Gregor20093b42009-12-09 23:02:17 +00005192 case FK_ArrayNeedsInitList:
5193 case FK_ArrayNeedsInitListOrStringLiteral:
5194 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5195 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5196 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005197
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005198 case FK_ArrayTypeMismatch:
5199 case FK_NonConstantArrayInit:
5200 S.Diag(Kind.getLocation(),
5201 (Failure == FK_ArrayTypeMismatch
5202 ? diag::err_array_init_different_type
5203 : diag::err_array_init_non_constant_array))
5204 << DestType.getNonReferenceType()
5205 << Args[0]->getType()
5206 << Args[0]->getSourceRange();
5207 break;
5208
John McCall73076432012-01-05 00:13:19 +00005209 case FK_VariableLengthArrayHasInitializer:
5210 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5211 << Args[0]->getSourceRange();
5212 break;
5213
John McCall6bb80172010-03-30 21:47:33 +00005214 case FK_AddressOfOverloadFailed: {
5215 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005216 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005217 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005218 true,
5219 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005220 break;
John McCall6bb80172010-03-30 21:47:33 +00005221 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005222
Douglas Gregor20093b42009-12-09 23:02:17 +00005223 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005224 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005225 switch (FailedOverloadResult) {
5226 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005227 if (Failure == FK_UserConversionOverloadFailed)
5228 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5229 << Args[0]->getType() << DestType
5230 << Args[0]->getSourceRange();
5231 else
5232 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5233 << DestType << Args[0]->getType()
5234 << Args[0]->getSourceRange();
5235
John McCall120d63c2010-08-24 20:38:10 +00005236 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005237 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005238
Douglas Gregor20093b42009-12-09 23:02:17 +00005239 case OR_No_Viable_Function:
5240 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5241 << Args[0]->getType() << DestType.getNonReferenceType()
5242 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00005243 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005244 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245
Douglas Gregor20093b42009-12-09 23:02:17 +00005246 case OR_Deleted: {
5247 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5248 << Args[0]->getType() << DestType.getNonReferenceType()
5249 << Args[0]->getSourceRange();
5250 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005251 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005252 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5253 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005254 if (Ovl == OR_Deleted) {
5255 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005256 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00005257 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005258 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005259 }
5260 break;
5261 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262
Douglas Gregor20093b42009-12-09 23:02:17 +00005263 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005264 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005265 }
5266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005267
Douglas Gregor20093b42009-12-09 23:02:17 +00005268 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005269 if (isa<InitListExpr>(Args[0])) {
5270 S.Diag(Kind.getLocation(),
5271 diag::err_lvalue_reference_bind_to_initlist)
5272 << DestType.getNonReferenceType().isVolatileQualified()
5273 << DestType.getNonReferenceType()
5274 << Args[0]->getSourceRange();
5275 break;
5276 }
5277 // Intentional fallthrough
5278
Douglas Gregor20093b42009-12-09 23:02:17 +00005279 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005280 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005281 Failure == FK_NonConstLValueReferenceBindingToTemporary
5282 ? diag::err_lvalue_reference_bind_to_temporary
5283 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005284 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005285 << DestType.getNonReferenceType()
5286 << Args[0]->getType()
5287 << Args[0]->getSourceRange();
5288 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005289
Douglas Gregor20093b42009-12-09 23:02:17 +00005290 case FK_RValueReferenceBindingToLValue:
5291 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005292 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005293 << Args[0]->getSourceRange();
5294 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005295
Douglas Gregor20093b42009-12-09 23:02:17 +00005296 case FK_ReferenceInitDropsQualifiers:
5297 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5298 << DestType.getNonReferenceType()
5299 << Args[0]->getType()
5300 << Args[0]->getSourceRange();
5301 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005302
Douglas Gregor20093b42009-12-09 23:02:17 +00005303 case FK_ReferenceInitFailed:
5304 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5305 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005306 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005307 << Args[0]->getType()
5308 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005309 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5310 Args[0]->getType()->isObjCObjectPointerType())
5311 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005312 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005313
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005314 case FK_ConversionFailed: {
5315 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005316 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005317 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005318 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005319 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005320 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005321 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005322 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5323 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005324 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5325 Args[0]->getType()->isObjCObjectPointerType())
5326 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005327 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005328 }
John Wiegley429bb272011-04-08 18:41:53 +00005329
5330 case FK_ConversionFromPropertyFailed:
5331 // No-op. This error has already been reported.
5332 break;
5333
Douglas Gregord87b61f2009-12-10 17:56:55 +00005334 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005335 SourceRange R;
5336
5337 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005338 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005339 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005340 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005341 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005342
Douglas Gregor19311e72010-09-08 21:40:08 +00005343 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5344 if (Kind.isCStyleOrFunctionalCast())
5345 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5346 << R;
5347 else
5348 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5349 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005350 break;
5351 }
5352
5353 case FK_ReferenceBindingToInitList:
5354 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5355 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5356 break;
5357
5358 case FK_InitListBadDestinationType:
5359 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5360 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5361 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005362
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005363 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005364 case FK_ConstructorOverloadFailed: {
5365 SourceRange ArgsRange;
5366 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005367 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005368 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005369
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005370 if (Failure == FK_ListConstructorOverloadFailed) {
5371 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5372 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5373 Args = InitList->getInits();
5374 NumArgs = InitList->getNumInits();
5375 }
5376
Douglas Gregor51c56d62009-12-14 20:49:26 +00005377 // FIXME: Using "DestType" for the entity we're printing is probably
5378 // bad.
5379 switch (FailedOverloadResult) {
5380 case OR_Ambiguous:
5381 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5382 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005383 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5384 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005385 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005386
Douglas Gregor51c56d62009-12-14 20:49:26 +00005387 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005388 if (Kind.getKind() == InitializationKind::IK_Default &&
5389 (Entity.getKind() == InitializedEntity::EK_Base ||
5390 Entity.getKind() == InitializedEntity::EK_Member) &&
5391 isa<CXXConstructorDecl>(S.CurContext)) {
5392 // This is implicit default initialization of a member or
5393 // base within a constructor. If no viable function was
5394 // found, notify the user that she needs to explicitly
5395 // initialize this base/member.
5396 CXXConstructorDecl *Constructor
5397 = cast<CXXConstructorDecl>(S.CurContext);
5398 if (Entity.getKind() == InitializedEntity::EK_Base) {
5399 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5400 << Constructor->isImplicit()
5401 << S.Context.getTypeDeclType(Constructor->getParent())
5402 << /*base=*/0
5403 << Entity.getType();
5404
5405 RecordDecl *BaseDecl
5406 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5407 ->getDecl();
5408 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5409 << S.Context.getTagDeclType(BaseDecl);
5410 } else {
5411 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5412 << Constructor->isImplicit()
5413 << S.Context.getTypeDeclType(Constructor->getParent())
5414 << /*member=*/1
5415 << Entity.getName();
5416 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5417
5418 if (const RecordType *Record
5419 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005420 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005421 diag::note_previous_decl)
5422 << S.Context.getTagDeclType(Record->getDecl());
5423 }
5424 break;
5425 }
5426
Douglas Gregor51c56d62009-12-14 20:49:26 +00005427 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5428 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005429 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005430 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005431
Douglas Gregor51c56d62009-12-14 20:49:26 +00005432 case OR_Deleted: {
5433 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5434 << true << DestType << ArgsRange;
5435 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005436 OverloadingResult Ovl
5437 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005438 if (Ovl == OR_Deleted) {
5439 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005440 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005441 } else {
5442 llvm_unreachable("Inconsistent overload resolution?");
5443 }
5444 break;
5445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005446
Douglas Gregor51c56d62009-12-14 20:49:26 +00005447 case OR_Success:
5448 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00005449 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005450 }
David Blaikie9fdefb32012-01-17 08:24:58 +00005451 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005452
Douglas Gregor99a2e602009-12-16 01:38:02 +00005453 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005454 if (Entity.getKind() == InitializedEntity::EK_Member &&
5455 isa<CXXConstructorDecl>(S.CurContext)) {
5456 // This is implicit default-initialization of a const member in
5457 // a constructor. Complain that it needs to be explicitly
5458 // initialized.
5459 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5460 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5461 << Constructor->isImplicit()
5462 << S.Context.getTypeDeclType(Constructor->getParent())
5463 << /*const=*/1
5464 << Entity.getName();
5465 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5466 << Entity.getName();
5467 } else {
5468 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5469 << DestType << (bool)DestType->getAs<RecordType>();
5470 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005471 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005472
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005473 case FK_Incomplete:
5474 S.RequireCompleteType(Kind.getLocation(), DestType,
5475 diag::err_init_incomplete_type);
5476 break;
5477
Sebastian Redl14b0c192011-09-24 17:48:00 +00005478 case FK_ListInitializationFailed: {
5479 // Run the init list checker again to emit diagnostics.
5480 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5481 QualType DestType = Entity.getType();
5482 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005483 DestType, /*VerifyOnly=*/false,
5484 Kind.getKind() != InitializationKind::IK_Direct ||
5485 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005486 assert(DiagnoseInitList.HadError() &&
5487 "Inconsistent init list check result.");
5488 break;
5489 }
John McCall5acb0c92011-10-17 18:40:02 +00005490
5491 case FK_PlaceholderType: {
5492 // FIXME: Already diagnosed!
5493 break;
5494 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00005495
5496 case FK_InitListElementCopyFailure: {
5497 // Try to perform all copies again.
5498 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5499 unsigned NumInits = InitList->getNumInits();
5500 QualType DestType = Entity.getType();
5501 QualType E;
5502 bool Success = S.isStdInitializerList(DestType, &E);
5503 (void)Success;
5504 assert(Success && "Where did the std::initializer_list go?");
5505 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5506 S.Context.getConstantArrayType(E,
5507 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5508 NumInits),
5509 ArrayType::Normal, 0));
5510 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5511 0, HiddenArray);
5512 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5513 // where the init list type is wrong, e.g.
5514 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5515 // FIXME: Emit a note if we hit the limit?
5516 int ErrorCount = 0;
5517 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5518 Element.setElementIndex(i);
5519 ExprResult Init = S.Owned(InitList->getInit(i));
5520 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5521 .isInvalid())
5522 ++ErrorCount;
5523 }
5524 break;
5525 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005526 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005527
Douglas Gregora41a8c52010-04-22 00:20:18 +00005528 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005529 return true;
5530}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005531
Chris Lattner5f9e2722011-07-23 10:55:15 +00005532void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005533 switch (SequenceKind) {
5534 case FailedSequence: {
5535 OS << "Failed sequence: ";
5536 switch (Failure) {
5537 case FK_TooManyInitsForReference:
5538 OS << "too many initializers for reference";
5539 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005540
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005541 case FK_ArrayNeedsInitList:
5542 OS << "array requires initializer list";
5543 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005544
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005545 case FK_ArrayNeedsInitListOrStringLiteral:
5546 OS << "array requires initializer list or string literal";
5547 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005548
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005549 case FK_ArrayTypeMismatch:
5550 OS << "array type mismatch";
5551 break;
5552
5553 case FK_NonConstantArrayInit:
5554 OS << "non-constant array initializer";
5555 break;
5556
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005557 case FK_AddressOfOverloadFailed:
5558 OS << "address of overloaded function failed";
5559 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005560
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005561 case FK_ReferenceInitOverloadFailed:
5562 OS << "overload resolution for reference initialization failed";
5563 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005564
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005565 case FK_NonConstLValueReferenceBindingToTemporary:
5566 OS << "non-const lvalue reference bound to temporary";
5567 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005568
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005569 case FK_NonConstLValueReferenceBindingToUnrelated:
5570 OS << "non-const lvalue reference bound to unrelated type";
5571 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005572
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005573 case FK_RValueReferenceBindingToLValue:
5574 OS << "rvalue reference bound to an lvalue";
5575 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005576
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005577 case FK_ReferenceInitDropsQualifiers:
5578 OS << "reference initialization drops qualifiers";
5579 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005580
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005581 case FK_ReferenceInitFailed:
5582 OS << "reference initialization failed";
5583 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005584
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005585 case FK_ConversionFailed:
5586 OS << "conversion failed";
5587 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005588
John Wiegley429bb272011-04-08 18:41:53 +00005589 case FK_ConversionFromPropertyFailed:
5590 OS << "conversion from property failed";
5591 break;
5592
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005593 case FK_TooManyInitsForScalar:
5594 OS << "too many initializers for scalar";
5595 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005596
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005597 case FK_ReferenceBindingToInitList:
5598 OS << "referencing binding to initializer list";
5599 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005600
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005601 case FK_InitListBadDestinationType:
5602 OS << "initializer list for non-aggregate, non-scalar type";
5603 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005604
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005605 case FK_UserConversionOverloadFailed:
5606 OS << "overloading failed for user-defined conversion";
5607 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005608
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005609 case FK_ConstructorOverloadFailed:
5610 OS << "constructor overloading failed";
5611 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005612
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005613 case FK_DefaultInitOfConst:
5614 OS << "default initialization of a const variable";
5615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005616
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005617 case FK_Incomplete:
5618 OS << "initialization of incomplete type";
5619 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005620
5621 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005622 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005623 break;
5624
John McCall73076432012-01-05 00:13:19 +00005625 case FK_VariableLengthArrayHasInitializer:
5626 OS << "variable length array has an initializer";
5627 break;
5628
John McCall5acb0c92011-10-17 18:40:02 +00005629 case FK_PlaceholderType:
5630 OS << "initializer expression isn't contextually valid";
5631 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005632
5633 case FK_ListConstructorOverloadFailed:
5634 OS << "list constructor overloading failed";
5635 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005636
5637 case FK_InitListElementCopyFailure:
5638 OS << "copy construction of initializer list element failed";
5639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005640 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005641 OS << '\n';
5642 return;
5643 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005645 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005646 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005647 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005648
Sebastian Redl7491c492011-06-05 13:59:11 +00005649 case NormalSequence:
5650 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005651 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005652 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005653
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005654 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5655 if (S != step_begin()) {
5656 OS << " -> ";
5657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005658
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005659 switch (S->Kind) {
5660 case SK_ResolveAddressOfOverloadedFunction:
5661 OS << "resolve address of overloaded function";
5662 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005663
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005664 case SK_CastDerivedToBaseRValue:
5665 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5666 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667
Sebastian Redl906082e2010-07-20 04:20:21 +00005668 case SK_CastDerivedToBaseXValue:
5669 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5670 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005671
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005672 case SK_CastDerivedToBaseLValue:
5673 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5674 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005675
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005676 case SK_BindReference:
5677 OS << "bind reference to lvalue";
5678 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005679
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005680 case SK_BindReferenceToTemporary:
5681 OS << "bind reference to a temporary";
5682 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005683
Douglas Gregor523d46a2010-04-18 07:40:54 +00005684 case SK_ExtraneousCopyToTemporary:
5685 OS << "extraneous C++03 copy to temporary";
5686 break;
5687
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005688 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005689 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005690 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005691
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005692 case SK_QualificationConversionRValue:
5693 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005694 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005695
Sebastian Redl906082e2010-07-20 04:20:21 +00005696 case SK_QualificationConversionXValue:
5697 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005698 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005699
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005700 case SK_QualificationConversionLValue:
5701 OS << "qualification conversion (lvalue)";
5702 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005703
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005704 case SK_ConversionSequence:
5705 OS << "implicit conversion sequence (";
5706 S->ICS->DebugPrint(); // FIXME: use OS
5707 OS << ")";
5708 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005709
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005710 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005711 OS << "list aggregate initialization";
5712 break;
5713
5714 case SK_ListConstructorCall:
5715 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005716 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005717
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005718 case SK_UnwrapInitList:
5719 OS << "unwrap reference initializer list";
5720 break;
5721
5722 case SK_RewrapInitList:
5723 OS << "rewrap reference initializer list";
5724 break;
5725
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005726 case SK_ConstructorInitialization:
5727 OS << "constructor initialization";
5728 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005729
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005730 case SK_ZeroInitialization:
5731 OS << "zero initialization";
5732 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005733
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005734 case SK_CAssignment:
5735 OS << "C assignment";
5736 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005737
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005738 case SK_StringInit:
5739 OS << "string initialization";
5740 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005741
5742 case SK_ObjCObjectConversion:
5743 OS << "Objective-C object conversion";
5744 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005745
5746 case SK_ArrayInit:
5747 OS << "array initialization";
5748 break;
John McCallf85e1932011-06-15 23:02:42 +00005749
5750 case SK_PassByIndirectCopyRestore:
5751 OS << "pass by indirect copy and restore";
5752 break;
5753
5754 case SK_PassByIndirectRestore:
5755 OS << "pass by indirect restore";
5756 break;
5757
5758 case SK_ProduceObjCObject:
5759 OS << "Objective-C object retension";
5760 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005761
5762 case SK_StdInitializerList:
5763 OS << "std::initializer_list from initializer list";
5764 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005765 }
5766 }
5767}
5768
5769void InitializationSequence::dump() const {
5770 dump(llvm::errs());
5771}
5772
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005773static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5774 QualType EntityType,
5775 const Expr *PreInit,
5776 const Expr *PostInit) {
5777 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5778 return;
5779
5780 // A narrowing conversion can only appear as the final implicit conversion in
5781 // an initialization sequence.
5782 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5783 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5784 return;
5785
5786 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5787 const StandardConversionSequence *SCS = 0;
5788 switch (ICS.getKind()) {
5789 case ImplicitConversionSequence::StandardConversion:
5790 SCS = &ICS.Standard;
5791 break;
5792 case ImplicitConversionSequence::UserDefinedConversion:
5793 SCS = &ICS.UserDefined.After;
5794 break;
5795 case ImplicitConversionSequence::AmbiguousConversion:
5796 case ImplicitConversionSequence::EllipsisConversion:
5797 case ImplicitConversionSequence::BadConversion:
5798 return;
5799 }
5800
5801 // Determine the type prior to the narrowing conversion. If a conversion
5802 // operator was used, this may be different from both the type of the entity
5803 // and of the pre-initialization expression.
5804 QualType PreNarrowingType = PreInit->getType();
5805 if (Seq.step_begin() + 1 != Seq.step_end())
5806 PreNarrowingType = Seq.step_end()[-2].Type;
5807
5808 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5809 APValue ConstantValue;
Richard Smith8ef7b202012-01-18 23:55:52 +00005810 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005811 case NK_Not_Narrowing:
5812 // No narrowing occurred.
5813 return;
5814
5815 case NK_Type_Narrowing:
5816 // This was a floating-to-integer conversion, which is always considered a
5817 // narrowing conversion even if the value is a constant and can be
5818 // represented exactly as an integer.
5819 S.Diag(PostInit->getLocStart(),
5820 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
5821 ? diag::err_init_list_type_narrowing
5822 : diag::warn_init_list_type_narrowing)
5823 << PostInit->getSourceRange()
5824 << PreNarrowingType.getLocalUnqualifiedType()
5825 << EntityType.getLocalUnqualifiedType();
5826 break;
5827
5828 case NK_Constant_Narrowing:
5829 // A constant value was narrowed.
5830 S.Diag(PostInit->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005831 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005832 ? diag::err_init_list_constant_narrowing
5833 : diag::warn_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005834 << PostInit->getSourceRange()
Richard Smith08d6e032011-12-16 19:06:07 +00005835 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005836 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005837 break;
5838
5839 case NK_Variable_Narrowing:
5840 // A variable's value may have been narrowed.
5841 S.Diag(PostInit->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005842 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005843 ? diag::err_init_list_variable_narrowing
5844 : diag::warn_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005845 << PostInit->getSourceRange()
5846 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005847 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005848 break;
5849 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005850
5851 llvm::SmallString<128> StaticCast;
5852 llvm::raw_svector_ostream OS(StaticCast);
5853 OS << "static_cast<";
5854 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5855 // It's important to use the typedef's name if there is one so that the
5856 // fixit doesn't break code using types like int64_t.
5857 //
5858 // FIXME: This will break if the typedef requires qualification. But
5859 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005860 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005861 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5862 OS << BT->getName(S.getLangOptions());
5863 else {
5864 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5865 // with a broken cast.
5866 return;
5867 }
5868 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005869 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5870 << PostInit->getSourceRange()
5871 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005872 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005873 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005874}
5875
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005876//===----------------------------------------------------------------------===//
5877// Initialization helper functions
5878//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005879bool
5880Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5881 ExprResult Init) {
5882 if (Init.isInvalid())
5883 return false;
5884
5885 Expr *InitE = Init.get();
5886 assert(InitE && "No initialization expression");
5887
5888 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5889 SourceLocation());
5890 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005891 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005892}
5893
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005894ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005895Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5896 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005897 ExprResult Init,
5898 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005899 if (Init.isInvalid())
5900 return ExprError();
5901
John McCall15d7d122010-11-11 03:21:53 +00005902 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005903 assert(InitE && "No initialization expression?");
5904
5905 if (EqualLoc.isInvalid())
5906 EqualLoc = InitE->getLocStart();
5907
5908 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5909 EqualLoc);
5910 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5911 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005912
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005913 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5914
5915 if (!Result.isInvalid() && TopLevelOfInitList)
5916 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
5917 InitE, Result.get());
5918
5919 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005920}