SemaOverload.cpp revision 3fd95ce225393fe4a3623e429766a8c3f487ff9d
11b268ca467c924004286c97bac133db489cf43d0Ben Murdoch//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 21b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// 31b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// The LLVM Compiler Infrastructure 41b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// 51b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// This file is distributed under the University of Illinois Open Source 61b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// License. See LICENSE.TXT for details. 71b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// 81b268ca467c924004286c97bac133db489cf43d0Ben Murdoch//===----------------------------------------------------------------------===// 91b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// 101b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// This file provides Sema routines for C++ overloading. 111b268ca467c924004286c97bac133db489cf43d0Ben Murdoch// 121b268ca467c924004286c97bac133db489cf43d0Ben Murdoch//===----------------------------------------------------------------------===// 131b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 141b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "Sema.h" 151b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "SemaInherit.h" 161b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "clang/Basic/Diagnostic.h" 171b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "clang/Lex/Preprocessor.h" 181b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "clang/AST/ASTContext.h" 191b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "clang/AST/Expr.h" 201b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "clang/AST/ExprCXX.h" 211b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "clang/AST/TypeOrdering.h" 221b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "llvm/ADT/SmallPtrSet.h" 231b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "llvm/ADT/STLExtras.h" 241b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include "llvm/Support/Compiler.h" 251b268ca467c924004286c97bac133db489cf43d0Ben Murdoch#include <algorithm> 261b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 271b268ca467c924004286c97bac133db489cf43d0Ben Murdochnamespace clang { 281b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 291b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// GetConversionCategory - Retrieve the implicit conversion 301b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// category corresponding to the given implicit conversion kind. 311b268ca467c924004286c97bac133db489cf43d0Ben MurdochImplicitConversionCategory 321b268ca467c924004286c97bac133db489cf43d0Ben MurdochGetConversionCategory(ImplicitConversionKind Kind) { 331b268ca467c924004286c97bac133db489cf43d0Ben Murdoch static const ImplicitConversionCategory 341b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Category[(int)ICK_Num_Conversion_Kinds] = { 351b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Identity, 361b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Lvalue_Transformation, 371b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Lvalue_Transformation, 381b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Lvalue_Transformation, 391b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Qualification_Adjustment, 401b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Promotion, 411b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Promotion, 421b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Promotion, 431b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 441b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 451b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 461b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 471b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 481b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 491b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 501b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 511b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion, 521b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICC_Conversion 531b268ca467c924004286c97bac133db489cf43d0Ben Murdoch }; 541b268ca467c924004286c97bac133db489cf43d0Ben Murdoch return Category[(int)Kind]; 551b268ca467c924004286c97bac133db489cf43d0Ben Murdoch} 561b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 571b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// GetConversionRank - Retrieve the implicit conversion rank 581b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// corresponding to the given implicit conversion kind. 591b268ca467c924004286c97bac133db489cf43d0Ben MurdochImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 601b268ca467c924004286c97bac133db489cf43d0Ben Murdoch static const ImplicitConversionRank 611b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Rank[(int)ICK_Num_Conversion_Kinds] = { 621b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Exact_Match, 631b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Exact_Match, 641b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Exact_Match, 651b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Exact_Match, 661b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Exact_Match, 671b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Promotion, 681b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Promotion, 691b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Promotion, 701b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 711b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 721b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 731b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 741b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 751b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 761b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 771b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 781b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion, 791b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ICR_Conversion 801b268ca467c924004286c97bac133db489cf43d0Ben Murdoch }; 811b268ca467c924004286c97bac133db489cf43d0Ben Murdoch return Rank[(int)Kind]; 821b268ca467c924004286c97bac133db489cf43d0Ben Murdoch} 831b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 841b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// GetImplicitConversionName - Return the name of this kind of 851b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// implicit conversion. 861b268ca467c924004286c97bac133db489cf43d0Ben Murdochconst char* GetImplicitConversionName(ImplicitConversionKind Kind) { 871b268ca467c924004286c97bac133db489cf43d0Ben Murdoch static const char* Name[(int)ICK_Num_Conversion_Kinds] = { 881b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "No conversion", 891b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Lvalue-to-rvalue", 901b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Array-to-pointer", 911b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Function-to-pointer", 921b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Qualification", 931b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Integral promotion", 941b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Floating point promotion", 951b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Complex promotion", 961b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Integral conversion", 971b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Floating conversion", 981b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Complex conversion", 991b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Floating-integral conversion", 1001b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Complex-real conversion", 1011b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Pointer conversion", 1021b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Pointer-to-member conversion", 1031b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Boolean conversion", 1041b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Compatible-types conversion", 1051b268ca467c924004286c97bac133db489cf43d0Ben Murdoch "Derived-to-base conversion" 1061b268ca467c924004286c97bac133db489cf43d0Ben Murdoch }; 1071b268ca467c924004286c97bac133db489cf43d0Ben Murdoch return Name[Kind]; 1081b268ca467c924004286c97bac133db489cf43d0Ben Murdoch} 1091b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 1101b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// StandardConversionSequence - Set the standard conversion 1111b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// sequence to the identity conversion. 1121b268ca467c924004286c97bac133db489cf43d0Ben Murdochvoid StandardConversionSequence::setAsIdentityConversion() { 1131b268ca467c924004286c97bac133db489cf43d0Ben Murdoch First = ICK_Identity; 1141b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Second = ICK_Identity; 1151b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Third = ICK_Identity; 1161b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Deprecated = false; 1171b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ReferenceBinding = false; 1181b268ca467c924004286c97bac133db489cf43d0Ben Murdoch DirectBinding = false; 1191b268ca467c924004286c97bac133db489cf43d0Ben Murdoch CopyConstructor = 0; 1201b268ca467c924004286c97bac133db489cf43d0Ben Murdoch} 1211b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 1221b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// getRank - Retrieve the rank of this standard conversion sequence 1231b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 1241b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// implicit conversions. 1251b268ca467c924004286c97bac133db489cf43d0Ben MurdochImplicitConversionRank StandardConversionSequence::getRank() const { 1261b268ca467c924004286c97bac133db489cf43d0Ben Murdoch ImplicitConversionRank Rank = ICR_Exact_Match; 1271b268ca467c924004286c97bac133db489cf43d0Ben Murdoch if (GetConversionRank(First) > Rank) 1281b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Rank = GetConversionRank(First); 1291b268ca467c924004286c97bac133db489cf43d0Ben Murdoch if (GetConversionRank(Second) > Rank) 1301b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Rank = GetConversionRank(Second); 1311b268ca467c924004286c97bac133db489cf43d0Ben Murdoch if (GetConversionRank(Third) > Rank) 1321b268ca467c924004286c97bac133db489cf43d0Ben Murdoch Rank = GetConversionRank(Third); 1331b268ca467c924004286c97bac133db489cf43d0Ben Murdoch return Rank; 1341b268ca467c924004286c97bac133db489cf43d0Ben Murdoch} 1351b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 1361b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// isPointerConversionToBool - Determines whether this conversion is 1371b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// a conversion of a pointer or pointer-to-member to bool. This is 1381b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// used as part of the ranking of standard conversion sequences 1391b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// (C++ 13.3.3.2p4). 1401b268ca467c924004286c97bac133db489cf43d0Ben Murdochbool StandardConversionSequence::isPointerConversionToBool() const 1411b268ca467c924004286c97bac133db489cf43d0Ben Murdoch{ 1421b268ca467c924004286c97bac133db489cf43d0Ben Murdoch QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 1431b268ca467c924004286c97bac133db489cf43d0Ben Murdoch QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 1441b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 1451b268ca467c924004286c97bac133db489cf43d0Ben Murdoch // Note that FromType has not necessarily been transformed by the 1461b268ca467c924004286c97bac133db489cf43d0Ben Murdoch // array-to-pointer or function-to-pointer implicit conversions, so 1471b268ca467c924004286c97bac133db489cf43d0Ben Murdoch // check for their presence as well as checking whether FromType is 1481b268ca467c924004286c97bac133db489cf43d0Ben Murdoch // a pointer. 1491b268ca467c924004286c97bac133db489cf43d0Ben Murdoch if (ToType->isBooleanType() && 1501b268ca467c924004286c97bac133db489cf43d0Ben Murdoch (FromType->isPointerType() || FromType->isBlockPointerType() || 1511b268ca467c924004286c97bac133db489cf43d0Ben Murdoch First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 1521b268ca467c924004286c97bac133db489cf43d0Ben Murdoch return true; 1531b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 1541b268ca467c924004286c97bac133db489cf43d0Ben Murdoch return false; 1551b268ca467c924004286c97bac133db489cf43d0Ben Murdoch} 1561b268ca467c924004286c97bac133db489cf43d0Ben Murdoch 1571b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// isPointerConversionToVoidPointer - Determines whether this 1581b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// conversion is a conversion of a pointer to a void pointer. This is 1591b268ca467c924004286c97bac133db489cf43d0Ben Murdoch/// used as part of the ranking of standard conversion sequences (C++ 160/// 13.3.3.2p4). 161bool 162StandardConversionSequence:: 163isPointerConversionToVoidPointer(ASTContext& Context) const 164{ 165 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 166 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 167 168 // Note that FromType has not necessarily been transformed by the 169 // array-to-pointer implicit conversion, so check for its presence 170 // and redo the conversion to get a pointer. 171 if (First == ICK_Array_To_Pointer) 172 FromType = Context.getArrayDecayedType(FromType); 173 174 if (Second == ICK_Pointer_Conversion) 175 if (const PointerType* ToPtrType = ToType->getAsPointerType()) 176 return ToPtrType->getPointeeType()->isVoidType(); 177 178 return false; 179} 180 181/// DebugPrint - Print this standard conversion sequence to standard 182/// error. Useful for debugging overloading issues. 183void StandardConversionSequence::DebugPrint() const { 184 bool PrintedSomething = false; 185 if (First != ICK_Identity) { 186 fprintf(stderr, "%s", GetImplicitConversionName(First)); 187 PrintedSomething = true; 188 } 189 190 if (Second != ICK_Identity) { 191 if (PrintedSomething) { 192 fprintf(stderr, " -> "); 193 } 194 fprintf(stderr, "%s", GetImplicitConversionName(Second)); 195 196 if (CopyConstructor) { 197 fprintf(stderr, " (by copy constructor)"); 198 } else if (DirectBinding) { 199 fprintf(stderr, " (direct reference binding)"); 200 } else if (ReferenceBinding) { 201 fprintf(stderr, " (reference binding)"); 202 } 203 PrintedSomething = true; 204 } 205 206 if (Third != ICK_Identity) { 207 if (PrintedSomething) { 208 fprintf(stderr, " -> "); 209 } 210 fprintf(stderr, "%s", GetImplicitConversionName(Third)); 211 PrintedSomething = true; 212 } 213 214 if (!PrintedSomething) { 215 fprintf(stderr, "No conversions required"); 216 } 217} 218 219/// DebugPrint - Print this user-defined conversion sequence to standard 220/// error. Useful for debugging overloading issues. 221void UserDefinedConversionSequence::DebugPrint() const { 222 if (Before.First || Before.Second || Before.Third) { 223 Before.DebugPrint(); 224 fprintf(stderr, " -> "); 225 } 226 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str()); 227 if (After.First || After.Second || After.Third) { 228 fprintf(stderr, " -> "); 229 After.DebugPrint(); 230 } 231} 232 233/// DebugPrint - Print this implicit conversion sequence to standard 234/// error. Useful for debugging overloading issues. 235void ImplicitConversionSequence::DebugPrint() const { 236 switch (ConversionKind) { 237 case StandardConversion: 238 fprintf(stderr, "Standard conversion: "); 239 Standard.DebugPrint(); 240 break; 241 case UserDefinedConversion: 242 fprintf(stderr, "User-defined conversion: "); 243 UserDefined.DebugPrint(); 244 break; 245 case EllipsisConversion: 246 fprintf(stderr, "Ellipsis conversion"); 247 break; 248 case BadConversion: 249 fprintf(stderr, "Bad conversion"); 250 break; 251 } 252 253 fprintf(stderr, "\n"); 254} 255 256// IsOverload - Determine whether the given New declaration is an 257// overload of the Old declaration. This routine returns false if New 258// and Old cannot be overloaded, e.g., if they are functions with the 259// same signature (C++ 1.3.10) or if the Old declaration isn't a 260// function (or overload set). When it does return false and Old is an 261// OverloadedFunctionDecl, MatchedDecl will be set to point to the 262// FunctionDecl that New cannot be overloaded with. 263// 264// Example: Given the following input: 265// 266// void f(int, float); // #1 267// void f(int, int); // #2 268// int f(int, int); // #3 269// 270// When we process #1, there is no previous declaration of "f", 271// so IsOverload will not be used. 272// 273// When we process #2, Old is a FunctionDecl for #1. By comparing the 274// parameter types, we see that #1 and #2 are overloaded (since they 275// have different signatures), so this routine returns false; 276// MatchedDecl is unchanged. 277// 278// When we process #3, Old is an OverloadedFunctionDecl containing #1 279// and #2. We compare the signatures of #3 to #1 (they're overloaded, 280// so we do nothing) and then #3 to #2. Since the signatures of #3 and 281// #2 are identical (return types of functions are not part of the 282// signature), IsOverload returns false and MatchedDecl will be set to 283// point to the FunctionDecl for #2. 284bool 285Sema::IsOverload(FunctionDecl *New, Decl* OldD, 286 OverloadedFunctionDecl::function_iterator& MatchedDecl) 287{ 288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) { 289 // Is this new function an overload of every function in the 290 // overload set? 291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 292 FuncEnd = Ovl->function_end(); 293 for (; Func != FuncEnd; ++Func) { 294 if (!IsOverload(New, *Func, MatchedDecl)) { 295 MatchedDecl = Func; 296 return false; 297 } 298 } 299 300 // This function overloads every function in the overload set. 301 return true; 302 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) { 303 // Is the function New an overload of the function Old? 304 QualType OldQType = Context.getCanonicalType(Old->getType()); 305 QualType NewQType = Context.getCanonicalType(New->getType()); 306 307 // Compare the signatures (C++ 1.3.10) of the two functions to 308 // determine whether they are overloads. If we find any mismatch 309 // in the signature, they are overloads. 310 311 // If either of these functions is a K&R-style function (no 312 // prototype), then we consider them to have matching signatures. 313 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 314 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 315 return false; 316 317 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr()); 318 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr()); 319 320 // The signature of a function includes the types of its 321 // parameters (C++ 1.3.10), which includes the presence or absence 322 // of the ellipsis; see C++ DR 357). 323 if (OldQType != NewQType && 324 (OldType->getNumArgs() != NewType->getNumArgs() || 325 OldType->isVariadic() != NewType->isVariadic() || 326 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 327 NewType->arg_type_begin()))) 328 return true; 329 330 // If the function is a class member, its signature includes the 331 // cv-qualifiers (if any) on the function itself. 332 // 333 // As part of this, also check whether one of the member functions 334 // is static, in which case they are not overloads (C++ 335 // 13.1p2). While not part of the definition of the signature, 336 // this check is important to determine whether these functions 337 // can be overloaded. 338 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 339 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 340 if (OldMethod && NewMethod && 341 !OldMethod->isStatic() && !NewMethod->isStatic() && 342 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers()) 343 return true; 344 345 // The signatures match; this is not an overload. 346 return false; 347 } else { 348 // (C++ 13p1): 349 // Only function declarations can be overloaded; object and type 350 // declarations cannot be overloaded. 351 return false; 352 } 353} 354 355/// TryImplicitConversion - Attempt to perform an implicit conversion 356/// from the given expression (Expr) to the given type (ToType). This 357/// function returns an implicit conversion sequence that can be used 358/// to perform the initialization. Given 359/// 360/// void f(float f); 361/// void g(int i) { f(i); } 362/// 363/// this routine would produce an implicit conversion sequence to 364/// describe the initialization of f from i, which will be a standard 365/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 366/// 4.1) followed by a floating-integral conversion (C++ 4.9). 367// 368/// Note that this routine only determines how the conversion can be 369/// performed; it does not actually perform the conversion. As such, 370/// it will not produce any diagnostics if no conversion is available, 371/// but will instead return an implicit conversion sequence of kind 372/// "BadConversion". 373/// 374/// If @p SuppressUserConversions, then user-defined conversions are 375/// not permitted. 376/// If @p AllowExplicit, then explicit user-defined conversions are 377/// permitted. 378ImplicitConversionSequence 379Sema::TryImplicitConversion(Expr* From, QualType ToType, 380 bool SuppressUserConversions, 381 bool AllowExplicit) 382{ 383 ImplicitConversionSequence ICS; 384 if (IsStandardConversion(From, ToType, ICS.Standard)) 385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 386 else if (getLangOptions().CPlusPlus && 387 IsUserDefinedConversion(From, ToType, ICS.UserDefined, 388 !SuppressUserConversions, AllowExplicit)) { 389 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 390 // C++ [over.ics.user]p4: 391 // A conversion of an expression of class type to the same class 392 // type is given Exact Match rank, and a conversion of an 393 // expression of class type to a base class of that type is 394 // given Conversion rank, in spite of the fact that a copy 395 // constructor (i.e., a user-defined conversion function) is 396 // called for those cases. 397 if (CXXConstructorDecl *Constructor 398 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 399 QualType FromCanon 400 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 401 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 402 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 403 // Turn this into a "standard" conversion sequence, so that it 404 // gets ranked with standard conversion sequences. 405 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 406 ICS.Standard.setAsIdentityConversion(); 407 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr(); 408 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr(); 409 ICS.Standard.CopyConstructor = Constructor; 410 if (ToCanon != FromCanon) 411 ICS.Standard.Second = ICK_Derived_To_Base; 412 } 413 } 414 415 // C++ [over.best.ics]p4: 416 // However, when considering the argument of a user-defined 417 // conversion function that is a candidate by 13.3.1.3 when 418 // invoked for the copying of the temporary in the second step 419 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 420 // 13.3.1.6 in all cases, only standard conversion sequences and 421 // ellipsis conversion sequences are allowed. 422 if (SuppressUserConversions && 423 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) 424 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 425 } else 426 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 427 428 return ICS; 429} 430 431/// IsStandardConversion - Determines whether there is a standard 432/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 433/// expression From to the type ToType. Standard conversion sequences 434/// only consider non-class types; for conversions that involve class 435/// types, use TryImplicitConversion. If a conversion exists, SCS will 436/// contain the standard conversion sequence required to perform this 437/// conversion and this routine will return true. Otherwise, this 438/// routine will return false and the value of SCS is unspecified. 439bool 440Sema::IsStandardConversion(Expr* From, QualType ToType, 441 StandardConversionSequence &SCS) 442{ 443 QualType FromType = From->getType(); 444 445 // Standard conversions (C++ [conv]) 446 SCS.setAsIdentityConversion(); 447 SCS.Deprecated = false; 448 SCS.IncompatibleObjC = false; 449 SCS.FromTypePtr = FromType.getAsOpaquePtr(); 450 SCS.CopyConstructor = 0; 451 452 // There are no standard conversions for class types in C++, so 453 // abort early. When overloading in C, however, we do permit 454 if (FromType->isRecordType() || ToType->isRecordType()) { 455 if (getLangOptions().CPlusPlus) 456 return false; 457 458 // When we're overloading in C, we allow, as standard conversions, 459 } 460 461 // The first conversion can be an lvalue-to-rvalue conversion, 462 // array-to-pointer conversion, or function-to-pointer conversion 463 // (C++ 4p1). 464 465 // Lvalue-to-rvalue conversion (C++ 4.1): 466 // An lvalue (3.10) of a non-function, non-array type T can be 467 // converted to an rvalue. 468 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context); 469 if (argIsLvalue == Expr::LV_Valid && 470 !FromType->isFunctionType() && !FromType->isArrayType() && 471 !FromType->isOverloadType()) { 472 SCS.First = ICK_Lvalue_To_Rvalue; 473 474 // If T is a non-class type, the type of the rvalue is the 475 // cv-unqualified version of T. Otherwise, the type of the rvalue 476 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 477 // just strip the qualifiers because they don't matter. 478 479 // FIXME: Doesn't see through to qualifiers behind a typedef! 480 FromType = FromType.getUnqualifiedType(); 481 } 482 // Array-to-pointer conversion (C++ 4.2) 483 else if (FromType->isArrayType()) { 484 SCS.First = ICK_Array_To_Pointer; 485 486 // An lvalue or rvalue of type "array of N T" or "array of unknown 487 // bound of T" can be converted to an rvalue of type "pointer to 488 // T" (C++ 4.2p1). 489 FromType = Context.getArrayDecayedType(FromType); 490 491 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) { 492 // This conversion is deprecated. (C++ D.4). 493 SCS.Deprecated = true; 494 495 // For the purpose of ranking in overload resolution 496 // (13.3.3.1.1), this conversion is considered an 497 // array-to-pointer conversion followed by a qualification 498 // conversion (4.4). (C++ 4.2p2) 499 SCS.Second = ICK_Identity; 500 SCS.Third = ICK_Qualification; 501 SCS.ToTypePtr = ToType.getAsOpaquePtr(); 502 return true; 503 } 504 } 505 // Function-to-pointer conversion (C++ 4.3). 506 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 507 SCS.First = ICK_Function_To_Pointer; 508 509 // An lvalue of function type T can be converted to an rvalue of 510 // type "pointer to T." The result is a pointer to the 511 // function. (C++ 4.3p1). 512 FromType = Context.getPointerType(FromType); 513 } 514 // Address of overloaded function (C++ [over.over]). 515 else if (FunctionDecl *Fn 516 = ResolveAddressOfOverloadedFunction(From, ToType, false)) { 517 SCS.First = ICK_Function_To_Pointer; 518 519 // We were able to resolve the address of the overloaded function, 520 // so we can convert to the type of that function. 521 FromType = Fn->getType(); 522 if (ToType->isReferenceType()) 523 FromType = Context.getReferenceType(FromType); 524 else if (ToType->isMemberPointerType()) { 525 // Resolve address only succeeds if both sides are member pointers, 526 // but it doesn't have to be the same class. See DR 247. 527 // Note that this means that the type of &Derived::fn can be 528 // Ret (Base::*)(Args) if the fn overload actually found is from the 529 // base class, even if it was brought into the derived class via a 530 // using declaration. The standard isn't clear on this issue at all. 531 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 532 FromType = Context.getMemberPointerType(FromType, 533 Context.getTypeDeclType(M->getParent()).getTypePtr()); 534 } else 535 FromType = Context.getPointerType(FromType); 536 } 537 // We don't require any conversions for the first step. 538 else { 539 SCS.First = ICK_Identity; 540 } 541 542 // The second conversion can be an integral promotion, floating 543 // point promotion, integral conversion, floating point conversion, 544 // floating-integral conversion, pointer conversion, 545 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 546 // For overloading in C, this can also be a "compatible-type" 547 // conversion. 548 bool IncompatibleObjC = false; 549 if (Context.hasSameUnqualifiedType(FromType, ToType)) { 550 // The unqualified versions of the types are the same: there's no 551 // conversion to do. 552 SCS.Second = ICK_Identity; 553 } 554 // Integral promotion (C++ 4.5). 555 else if (IsIntegralPromotion(From, FromType, ToType)) { 556 SCS.Second = ICK_Integral_Promotion; 557 FromType = ToType.getUnqualifiedType(); 558 } 559 // Floating point promotion (C++ 4.6). 560 else if (IsFloatingPointPromotion(FromType, ToType)) { 561 SCS.Second = ICK_Floating_Promotion; 562 FromType = ToType.getUnqualifiedType(); 563 } 564 // Complex promotion (Clang extension) 565 else if (IsComplexPromotion(FromType, ToType)) { 566 SCS.Second = ICK_Complex_Promotion; 567 FromType = ToType.getUnqualifiedType(); 568 } 569 // Integral conversions (C++ 4.7). 570 // FIXME: isIntegralType shouldn't be true for enums in C++. 571 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) && 572 (ToType->isIntegralType() && !ToType->isEnumeralType())) { 573 SCS.Second = ICK_Integral_Conversion; 574 FromType = ToType.getUnqualifiedType(); 575 } 576 // Floating point conversions (C++ 4.8). 577 else if (FromType->isFloatingType() && ToType->isFloatingType()) { 578 SCS.Second = ICK_Floating_Conversion; 579 FromType = ToType.getUnqualifiedType(); 580 } 581 // Complex conversions (C99 6.3.1.6) 582 else if (FromType->isComplexType() && ToType->isComplexType()) { 583 SCS.Second = ICK_Complex_Conversion; 584 FromType = ToType.getUnqualifiedType(); 585 } 586 // Floating-integral conversions (C++ 4.9). 587 // FIXME: isIntegralType shouldn't be true for enums in C++. 588 else if ((FromType->isFloatingType() && 589 ToType->isIntegralType() && !ToType->isBooleanType() && 590 !ToType->isEnumeralType()) || 591 ((FromType->isIntegralType() || FromType->isEnumeralType()) && 592 ToType->isFloatingType())) { 593 SCS.Second = ICK_Floating_Integral; 594 FromType = ToType.getUnqualifiedType(); 595 } 596 // Complex-real conversions (C99 6.3.1.7) 597 else if ((FromType->isComplexType() && ToType->isArithmeticType()) || 598 (ToType->isComplexType() && FromType->isArithmeticType())) { 599 SCS.Second = ICK_Complex_Real; 600 FromType = ToType.getUnqualifiedType(); 601 } 602 // Pointer conversions (C++ 4.10). 603 else if (IsPointerConversion(From, FromType, ToType, FromType, 604 IncompatibleObjC)) { 605 SCS.Second = ICK_Pointer_Conversion; 606 SCS.IncompatibleObjC = IncompatibleObjC; 607 } 608 // Pointer to member conversions (4.11). 609 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) { 610 SCS.Second = ICK_Pointer_Member; 611 } 612 // Boolean conversions (C++ 4.12). 613 else if (ToType->isBooleanType() && 614 (FromType->isArithmeticType() || 615 FromType->isEnumeralType() || 616 FromType->isPointerType() || 617 FromType->isBlockPointerType() || 618 FromType->isMemberPointerType())) { 619 SCS.Second = ICK_Boolean_Conversion; 620 FromType = Context.BoolTy; 621 } 622 // Compatible conversions (Clang extension for C function overloading) 623 else if (!getLangOptions().CPlusPlus && 624 Context.typesAreCompatible(ToType, FromType)) { 625 SCS.Second = ICK_Compatible_Conversion; 626 } else { 627 // No second conversion required. 628 SCS.Second = ICK_Identity; 629 } 630 631 QualType CanonFrom; 632 QualType CanonTo; 633 // The third conversion can be a qualification conversion (C++ 4p1). 634 if (IsQualificationConversion(FromType, ToType)) { 635 SCS.Third = ICK_Qualification; 636 FromType = ToType; 637 CanonFrom = Context.getCanonicalType(FromType); 638 CanonTo = Context.getCanonicalType(ToType); 639 } else { 640 // No conversion required 641 SCS.Third = ICK_Identity; 642 643 // C++ [over.best.ics]p6: 644 // [...] Any difference in top-level cv-qualification is 645 // subsumed by the initialization itself and does not constitute 646 // a conversion. [...] 647 CanonFrom = Context.getCanonicalType(FromType); 648 CanonTo = Context.getCanonicalType(ToType); 649 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() && 650 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) { 651 FromType = ToType; 652 CanonFrom = CanonTo; 653 } 654 } 655 656 // If we have not converted the argument type to the parameter type, 657 // this is a bad conversion sequence. 658 if (CanonFrom != CanonTo) 659 return false; 660 661 SCS.ToTypePtr = FromType.getAsOpaquePtr(); 662 return true; 663} 664 665/// IsIntegralPromotion - Determines whether the conversion from the 666/// expression From (whose potentially-adjusted type is FromType) to 667/// ToType is an integral promotion (C++ 4.5). If so, returns true and 668/// sets PromotedType to the promoted type. 669bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) 670{ 671 const BuiltinType *To = ToType->getAsBuiltinType(); 672 // All integers are built-in. 673 if (!To) { 674 return false; 675 } 676 677 // An rvalue of type char, signed char, unsigned char, short int, or 678 // unsigned short int can be converted to an rvalue of type int if 679 // int can represent all the values of the source type; otherwise, 680 // the source rvalue can be converted to an rvalue of type unsigned 681 // int (C++ 4.5p1). 682 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) { 683 if (// We can promote any signed, promotable integer type to an int 684 (FromType->isSignedIntegerType() || 685 // We can promote any unsigned integer type whose size is 686 // less than int to an int. 687 (!FromType->isSignedIntegerType() && 688 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 689 return To->getKind() == BuiltinType::Int; 690 } 691 692 return To->getKind() == BuiltinType::UInt; 693 } 694 695 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 696 // can be converted to an rvalue of the first of the following types 697 // that can represent all the values of its underlying type: int, 698 // unsigned int, long, or unsigned long (C++ 4.5p2). 699 if ((FromType->isEnumeralType() || FromType->isWideCharType()) 700 && ToType->isIntegerType()) { 701 // Determine whether the type we're converting from is signed or 702 // unsigned. 703 bool FromIsSigned; 704 uint64_t FromSize = Context.getTypeSize(FromType); 705 if (const EnumType *FromEnumType = FromType->getAsEnumType()) { 706 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType(); 707 FromIsSigned = UnderlyingType->isSignedIntegerType(); 708 } else { 709 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 710 FromIsSigned = true; 711 } 712 713 // The types we'll try to promote to, in the appropriate 714 // order. Try each of these types. 715 QualType PromoteTypes[6] = { 716 Context.IntTy, Context.UnsignedIntTy, 717 Context.LongTy, Context.UnsignedLongTy , 718 Context.LongLongTy, Context.UnsignedLongLongTy 719 }; 720 for (int Idx = 0; Idx < 6; ++Idx) { 721 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 722 if (FromSize < ToSize || 723 (FromSize == ToSize && 724 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 725 // We found the type that we can promote to. If this is the 726 // type we wanted, we have a promotion. Otherwise, no 727 // promotion. 728 return Context.getCanonicalType(ToType).getUnqualifiedType() 729 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType(); 730 } 731 } 732 } 733 734 // An rvalue for an integral bit-field (9.6) can be converted to an 735 // rvalue of type int if int can represent all the values of the 736 // bit-field; otherwise, it can be converted to unsigned int if 737 // unsigned int can represent all the values of the bit-field. If 738 // the bit-field is larger yet, no integral promotion applies to 739 // it. If the bit-field has an enumerated type, it is treated as any 740 // other value of that type for promotion purposes (C++ 4.5p3). 741 // FIXME: We should delay checking of bit-fields until we actually 742 // perform the conversion. 743 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) { 744 using llvm::APSInt; 745 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) { 746 APSInt BitWidth; 747 if (MemberDecl->isBitField() && 748 FromType->isIntegralType() && !FromType->isEnumeralType() && 749 From->isIntegerConstantExpr(BitWidth, Context)) { 750 APSInt ToSize(Context.getTypeSize(ToType)); 751 752 // Are we promoting to an int from a bitfield that fits in an int? 753 if (BitWidth < ToSize || 754 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 755 return To->getKind() == BuiltinType::Int; 756 } 757 758 // Are we promoting to an unsigned int from an unsigned bitfield 759 // that fits into an unsigned int? 760 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 761 return To->getKind() == BuiltinType::UInt; 762 } 763 764 return false; 765 } 766 } 767 } 768 769 // An rvalue of type bool can be converted to an rvalue of type int, 770 // with false becoming zero and true becoming one (C++ 4.5p4). 771 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 772 return true; 773 } 774 775 return false; 776} 777 778/// IsFloatingPointPromotion - Determines whether the conversion from 779/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 780/// returns true and sets PromotedType to the promoted type. 781bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) 782{ 783 /// An rvalue of type float can be converted to an rvalue of type 784 /// double. (C++ 4.6p1). 785 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType()) 786 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) { 787 if (FromBuiltin->getKind() == BuiltinType::Float && 788 ToBuiltin->getKind() == BuiltinType::Double) 789 return true; 790 791 // C99 6.3.1.5p1: 792 // When a float is promoted to double or long double, or a 793 // double is promoted to long double [...]. 794 if (!getLangOptions().CPlusPlus && 795 (FromBuiltin->getKind() == BuiltinType::Float || 796 FromBuiltin->getKind() == BuiltinType::Double) && 797 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 798 return true; 799 } 800 801 return false; 802} 803 804/// \brief Determine if a conversion is a complex promotion. 805/// 806/// A complex promotion is defined as a complex -> complex conversion 807/// where the conversion between the underlying real types is a 808/// floating-point or integral promotion. 809bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 810 const ComplexType *FromComplex = FromType->getAsComplexType(); 811 if (!FromComplex) 812 return false; 813 814 const ComplexType *ToComplex = ToType->getAsComplexType(); 815 if (!ToComplex) 816 return false; 817 818 return IsFloatingPointPromotion(FromComplex->getElementType(), 819 ToComplex->getElementType()) || 820 IsIntegralPromotion(0, FromComplex->getElementType(), 821 ToComplex->getElementType()); 822} 823 824/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 825/// the pointer type FromPtr to a pointer to type ToPointee, with the 826/// same type qualifiers as FromPtr has on its pointee type. ToType, 827/// if non-empty, will be a pointer to ToType that may or may not have 828/// the right set of qualifiers on its pointee. 829static QualType 830BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr, 831 QualType ToPointee, QualType ToType, 832 ASTContext &Context) { 833 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType()); 834 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 835 unsigned Quals = CanonFromPointee.getCVRQualifiers(); 836 837 // Exact qualifier match -> return the pointer type we're converting to. 838 if (CanonToPointee.getCVRQualifiers() == Quals) { 839 // ToType is exactly what we need. Return it. 840 if (ToType.getTypePtr()) 841 return ToType; 842 843 // Build a pointer to ToPointee. It has the right qualifiers 844 // already. 845 return Context.getPointerType(ToPointee); 846 } 847 848 // Just build a canonical type that has the right qualifiers. 849 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals)); 850} 851 852/// IsPointerConversion - Determines whether the conversion of the 853/// expression From, which has the (possibly adjusted) type FromType, 854/// can be converted to the type ToType via a pointer conversion (C++ 855/// 4.10). If so, returns true and places the converted type (that 856/// might differ from ToType in its cv-qualifiers at some level) into 857/// ConvertedType. 858/// 859/// This routine also supports conversions to and from block pointers 860/// and conversions with Objective-C's 'id', 'id<protocols...>', and 861/// pointers to interfaces. FIXME: Once we've determined the 862/// appropriate overloading rules for Objective-C, we may want to 863/// split the Objective-C checks into a different routine; however, 864/// GCC seems to consider all of these conversions to be pointer 865/// conversions, so for now they live here. IncompatibleObjC will be 866/// set if the conversion is an allowed Objective-C conversion that 867/// should result in a warning. 868bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 869 QualType& ConvertedType, 870 bool &IncompatibleObjC) 871{ 872 IncompatibleObjC = false; 873 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC)) 874 return true; 875 876 // Conversion from a null pointer constant to any Objective-C pointer type. 877 if (Context.isObjCObjectPointerType(ToType) && 878 From->isNullPointerConstant(Context)) { 879 ConvertedType = ToType; 880 return true; 881 } 882 883 // Blocks: Block pointers can be converted to void*. 884 if (FromType->isBlockPointerType() && ToType->isPointerType() && 885 ToType->getAsPointerType()->getPointeeType()->isVoidType()) { 886 ConvertedType = ToType; 887 return true; 888 } 889 // Blocks: A null pointer constant can be converted to a block 890 // pointer type. 891 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) { 892 ConvertedType = ToType; 893 return true; 894 } 895 896 const PointerType* ToTypePtr = ToType->getAsPointerType(); 897 if (!ToTypePtr) 898 return false; 899 900 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 901 if (From->isNullPointerConstant(Context)) { 902 ConvertedType = ToType; 903 return true; 904 } 905 906 // Beyond this point, both types need to be pointers. 907 const PointerType *FromTypePtr = FromType->getAsPointerType(); 908 if (!FromTypePtr) 909 return false; 910 911 QualType FromPointeeType = FromTypePtr->getPointeeType(); 912 QualType ToPointeeType = ToTypePtr->getPointeeType(); 913 914 // An rvalue of type "pointer to cv T," where T is an object type, 915 // can be converted to an rvalue of type "pointer to cv void" (C++ 916 // 4.10p2). 917 if (FromPointeeType->isIncompleteOrObjectType() && 918 ToPointeeType->isVoidType()) { 919 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 920 ToPointeeType, 921 ToType, Context); 922 return true; 923 } 924 925 // When we're overloading in C, we allow a special kind of pointer 926 // conversion for compatible-but-not-identical pointee types. 927 if (!getLangOptions().CPlusPlus && 928 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 929 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 930 ToPointeeType, 931 ToType, Context); 932 return true; 933 } 934 935 // C++ [conv.ptr]p3: 936 // 937 // An rvalue of type "pointer to cv D," where D is a class type, 938 // can be converted to an rvalue of type "pointer to cv B," where 939 // B is a base class (clause 10) of D. If B is an inaccessible 940 // (clause 11) or ambiguous (10.2) base class of D, a program that 941 // necessitates this conversion is ill-formed. The result of the 942 // conversion is a pointer to the base class sub-object of the 943 // derived class object. The null pointer value is converted to 944 // the null pointer value of the destination type. 945 // 946 // Note that we do not check for ambiguity or inaccessibility 947 // here. That is handled by CheckPointerConversion. 948 if (getLangOptions().CPlusPlus && 949 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 950 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 951 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 952 ToPointeeType, 953 ToType, Context); 954 return true; 955 } 956 957 return false; 958} 959 960/// isObjCPointerConversion - Determines whether this is an 961/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 962/// with the same arguments and return values. 963bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 964 QualType& ConvertedType, 965 bool &IncompatibleObjC) { 966 if (!getLangOptions().ObjC1) 967 return false; 968 969 // Conversions with Objective-C's id<...>. 970 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) && 971 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) { 972 ConvertedType = ToType; 973 return true; 974 } 975 976 // Beyond this point, both types need to be pointers or block pointers. 977 QualType ToPointeeType; 978 const PointerType* ToTypePtr = ToType->getAsPointerType(); 979 if (ToTypePtr) 980 ToPointeeType = ToTypePtr->getPointeeType(); 981 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType()) 982 ToPointeeType = ToBlockPtr->getPointeeType(); 983 else 984 return false; 985 986 QualType FromPointeeType; 987 const PointerType *FromTypePtr = FromType->getAsPointerType(); 988 if (FromTypePtr) 989 FromPointeeType = FromTypePtr->getPointeeType(); 990 else if (const BlockPointerType *FromBlockPtr 991 = FromType->getAsBlockPointerType()) 992 FromPointeeType = FromBlockPtr->getPointeeType(); 993 else 994 return false; 995 996 // Objective C++: We're able to convert from a pointer to an 997 // interface to a pointer to a different interface. 998 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType(); 999 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType(); 1000 if (FromIface && ToIface && 1001 Context.canAssignObjCInterfaces(ToIface, FromIface)) { 1002 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1003 ToPointeeType, 1004 ToType, Context); 1005 return true; 1006 } 1007 1008 if (FromIface && ToIface && 1009 Context.canAssignObjCInterfaces(FromIface, ToIface)) { 1010 // Okay: this is some kind of implicit downcast of Objective-C 1011 // interfaces, which is permitted. However, we're going to 1012 // complain about it. 1013 IncompatibleObjC = true; 1014 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1015 ToPointeeType, 1016 ToType, Context); 1017 return true; 1018 } 1019 1020 // Objective C++: We're able to convert between "id" and a pointer 1021 // to any interface (in both directions). 1022 if ((FromIface && Context.isObjCIdStructType(ToPointeeType)) 1023 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) { 1024 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1025 ToPointeeType, 1026 ToType, Context); 1027 return true; 1028 } 1029 1030 // Objective C++: Allow conversions between the Objective-C "id" and 1031 // "Class", in either direction. 1032 if ((Context.isObjCIdStructType(FromPointeeType) && 1033 Context.isObjCClassStructType(ToPointeeType)) || 1034 (Context.isObjCClassStructType(FromPointeeType) && 1035 Context.isObjCIdStructType(ToPointeeType))) { 1036 ConvertedType = ToType; 1037 return true; 1038 } 1039 1040 // If we have pointers to pointers, recursively check whether this 1041 // is an Objective-C conversion. 1042 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 1043 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1044 IncompatibleObjC)) { 1045 // We always complain about this conversion. 1046 IncompatibleObjC = true; 1047 ConvertedType = ToType; 1048 return true; 1049 } 1050 1051 // If we have pointers to functions or blocks, check whether the only 1052 // differences in the argument and result types are in Objective-C 1053 // pointer conversions. If so, we permit the conversion (but 1054 // complain about it). 1055 const FunctionProtoType *FromFunctionType 1056 = FromPointeeType->getAsFunctionProtoType(); 1057 const FunctionProtoType *ToFunctionType 1058 = ToPointeeType->getAsFunctionProtoType(); 1059 if (FromFunctionType && ToFunctionType) { 1060 // If the function types are exactly the same, this isn't an 1061 // Objective-C pointer conversion. 1062 if (Context.getCanonicalType(FromPointeeType) 1063 == Context.getCanonicalType(ToPointeeType)) 1064 return false; 1065 1066 // Perform the quick checks that will tell us whether these 1067 // function types are obviously different. 1068 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 1069 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 1070 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 1071 return false; 1072 1073 bool HasObjCConversion = false; 1074 if (Context.getCanonicalType(FromFunctionType->getResultType()) 1075 == Context.getCanonicalType(ToFunctionType->getResultType())) { 1076 // Okay, the types match exactly. Nothing to do. 1077 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 1078 ToFunctionType->getResultType(), 1079 ConvertedType, IncompatibleObjC)) { 1080 // Okay, we have an Objective-C pointer conversion. 1081 HasObjCConversion = true; 1082 } else { 1083 // Function types are too different. Abort. 1084 return false; 1085 } 1086 1087 // Check argument types. 1088 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 1089 ArgIdx != NumArgs; ++ArgIdx) { 1090 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 1091 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 1092 if (Context.getCanonicalType(FromArgType) 1093 == Context.getCanonicalType(ToArgType)) { 1094 // Okay, the types match exactly. Nothing to do. 1095 } else if (isObjCPointerConversion(FromArgType, ToArgType, 1096 ConvertedType, IncompatibleObjC)) { 1097 // Okay, we have an Objective-C pointer conversion. 1098 HasObjCConversion = true; 1099 } else { 1100 // Argument types are too different. Abort. 1101 return false; 1102 } 1103 } 1104 1105 if (HasObjCConversion) { 1106 // We had an Objective-C conversion. Allow this pointer 1107 // conversion, but complain about it. 1108 ConvertedType = ToType; 1109 IncompatibleObjC = true; 1110 return true; 1111 } 1112 } 1113 1114 return false; 1115} 1116 1117/// CheckPointerConversion - Check the pointer conversion from the 1118/// expression From to the type ToType. This routine checks for 1119/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 1120/// conversions for which IsPointerConversion has already returned 1121/// true. It returns true and produces a diagnostic if there was an 1122/// error, or returns false otherwise. 1123bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 1124 QualType FromType = From->getType(); 1125 1126 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 1127 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 1128 QualType FromPointeeType = FromPtrType->getPointeeType(), 1129 ToPointeeType = ToPtrType->getPointeeType(); 1130 1131 // Objective-C++ conversions are always okay. 1132 // FIXME: We should have a different class of conversions for 1133 // the Objective-C++ implicit conversions. 1134 if (Context.isObjCIdStructType(FromPointeeType) || 1135 Context.isObjCIdStructType(ToPointeeType) || 1136 Context.isObjCClassStructType(FromPointeeType) || 1137 Context.isObjCClassStructType(ToPointeeType)) 1138 return false; 1139 1140 if (FromPointeeType->isRecordType() && 1141 ToPointeeType->isRecordType()) { 1142 // We must have a derived-to-base conversion. Check an 1143 // ambiguous or inaccessible conversion. 1144 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 1145 From->getExprLoc(), 1146 From->getSourceRange()); 1147 } 1148 } 1149 1150 return false; 1151} 1152 1153/// IsMemberPointerConversion - Determines whether the conversion of the 1154/// expression From, which has the (possibly adjusted) type FromType, can be 1155/// converted to the type ToType via a member pointer conversion (C++ 4.11). 1156/// If so, returns true and places the converted type (that might differ from 1157/// ToType in its cv-qualifiers at some level) into ConvertedType. 1158bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 1159 QualType ToType, QualType &ConvertedType) 1160{ 1161 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType(); 1162 if (!ToTypePtr) 1163 return false; 1164 1165 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 1166 if (From->isNullPointerConstant(Context)) { 1167 ConvertedType = ToType; 1168 return true; 1169 } 1170 1171 // Otherwise, both types have to be member pointers. 1172 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType(); 1173 if (!FromTypePtr) 1174 return false; 1175 1176 // A pointer to member of B can be converted to a pointer to member of D, 1177 // where D is derived from B (C++ 4.11p2). 1178 QualType FromClass(FromTypePtr->getClass(), 0); 1179 QualType ToClass(ToTypePtr->getClass(), 0); 1180 // FIXME: What happens when these are dependent? Is this function even called? 1181 1182 if (IsDerivedFrom(ToClass, FromClass)) { 1183 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 1184 ToClass.getTypePtr()); 1185 return true; 1186 } 1187 1188 return false; 1189} 1190 1191/// CheckMemberPointerConversion - Check the member pointer conversion from the 1192/// expression From to the type ToType. This routine checks for ambiguous or 1193/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions 1194/// for which IsMemberPointerConversion has already returned true. It returns 1195/// true and produces a diagnostic if there was an error, or returns false 1196/// otherwise. 1197bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) { 1198 QualType FromType = From->getType(); 1199 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType(); 1200 if (!FromPtrType) 1201 return false; 1202 1203 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType(); 1204 assert(ToPtrType && "No member pointer cast has a target type " 1205 "that is not a member pointer."); 1206 1207 QualType FromClass = QualType(FromPtrType->getClass(), 0); 1208 QualType ToClass = QualType(ToPtrType->getClass(), 0); 1209 1210 // FIXME: What about dependent types? 1211 assert(FromClass->isRecordType() && "Pointer into non-class."); 1212 assert(ToClass->isRecordType() && "Pointer into non-class."); 1213 1214 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1215 /*DetectVirtual=*/true); 1216 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 1217 assert(DerivationOkay && 1218 "Should not have been called if derivation isn't OK."); 1219 (void)DerivationOkay; 1220 1221 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 1222 getUnqualifiedType())) { 1223 // Derivation is ambiguous. Redo the check to find the exact paths. 1224 Paths.clear(); 1225 Paths.setRecordingPaths(true); 1226 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths); 1227 assert(StillOkay && "Derivation changed due to quantum fluctuation."); 1228 (void)StillOkay; 1229 1230 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1231 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 1232 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 1233 return true; 1234 } 1235 1236 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1237 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 1238 << FromClass << ToClass << QualType(VBase, 0) 1239 << From->getSourceRange(); 1240 return true; 1241 } 1242 1243 return false; 1244} 1245 1246/// IsQualificationConversion - Determines whether the conversion from 1247/// an rvalue of type FromType to ToType is a qualification conversion 1248/// (C++ 4.4). 1249bool 1250Sema::IsQualificationConversion(QualType FromType, QualType ToType) 1251{ 1252 FromType = Context.getCanonicalType(FromType); 1253 ToType = Context.getCanonicalType(ToType); 1254 1255 // If FromType and ToType are the same type, this is not a 1256 // qualification conversion. 1257 if (FromType == ToType) 1258 return false; 1259 1260 // (C++ 4.4p4): 1261 // A conversion can add cv-qualifiers at levels other than the first 1262 // in multi-level pointers, subject to the following rules: [...] 1263 bool PreviousToQualsIncludeConst = true; 1264 bool UnwrappedAnyPointer = false; 1265 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 1266 // Within each iteration of the loop, we check the qualifiers to 1267 // determine if this still looks like a qualification 1268 // conversion. Then, if all is well, we unwrap one more level of 1269 // pointers or pointers-to-members and do it all again 1270 // until there are no more pointers or pointers-to-members left to 1271 // unwrap. 1272 UnwrappedAnyPointer = true; 1273 1274 // -- for every j > 0, if const is in cv 1,j then const is in cv 1275 // 2,j, and similarly for volatile. 1276 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 1277 return false; 1278 1279 // -- if the cv 1,j and cv 2,j are different, then const is in 1280 // every cv for 0 < k < j. 1281 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 1282 && !PreviousToQualsIncludeConst) 1283 return false; 1284 1285 // Keep track of whether all prior cv-qualifiers in the "to" type 1286 // include const. 1287 PreviousToQualsIncludeConst 1288 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 1289 } 1290 1291 // We are left with FromType and ToType being the pointee types 1292 // after unwrapping the original FromType and ToType the same number 1293 // of types. If we unwrapped any pointers, and if FromType and 1294 // ToType have the same unqualified type (since we checked 1295 // qualifiers above), then this is a qualification conversion. 1296 return UnwrappedAnyPointer && 1297 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 1298} 1299 1300/// Determines whether there is a user-defined conversion sequence 1301/// (C++ [over.ics.user]) that converts expression From to the type 1302/// ToType. If such a conversion exists, User will contain the 1303/// user-defined conversion sequence that performs such a conversion 1304/// and this routine will return true. Otherwise, this routine returns 1305/// false and User is unspecified. 1306/// 1307/// \param AllowConversionFunctions true if the conversion should 1308/// consider conversion functions at all. If false, only constructors 1309/// will be considered. 1310/// 1311/// \param AllowExplicit true if the conversion should consider C++0x 1312/// "explicit" conversion functions as well as non-explicit conversion 1313/// functions (C++0x [class.conv.fct]p2). 1314bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 1315 UserDefinedConversionSequence& User, 1316 bool AllowConversionFunctions, 1317 bool AllowExplicit) 1318{ 1319 OverloadCandidateSet CandidateSet; 1320 if (const RecordType *ToRecordType = ToType->getAsRecordType()) { 1321 if (CXXRecordDecl *ToRecordDecl 1322 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 1323 // C++ [over.match.ctor]p1: 1324 // When objects of class type are direct-initialized (8.5), or 1325 // copy-initialized from an expression of the same or a 1326 // derived class type (8.5), overload resolution selects the 1327 // constructor. [...] For copy-initialization, the candidate 1328 // functions are all the converting constructors (12.3.1) of 1329 // that class. The argument list is the expression-list within 1330 // the parentheses of the initializer. 1331 DeclarationName ConstructorName 1332 = Context.DeclarationNames.getCXXConstructorName( 1333 Context.getCanonicalType(ToType).getUnqualifiedType()); 1334 DeclContext::lookup_iterator Con, ConEnd; 1335 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName); 1336 Con != ConEnd; ++Con) { 1337 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1338 if (Constructor->isConvertingConstructor()) 1339 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1340 /*SuppressUserConversions=*/true); 1341 } 1342 } 1343 } 1344 1345 if (!AllowConversionFunctions) { 1346 // Don't allow any conversion functions to enter the overload set. 1347 } else if (const RecordType *FromRecordType 1348 = From->getType()->getAsRecordType()) { 1349 if (CXXRecordDecl *FromRecordDecl 1350 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 1351 // Add all of the conversion functions as candidates. 1352 // FIXME: Look for conversions in base classes! 1353 OverloadedFunctionDecl *Conversions 1354 = FromRecordDecl->getConversionFunctions(); 1355 for (OverloadedFunctionDecl::function_iterator Func 1356 = Conversions->function_begin(); 1357 Func != Conversions->function_end(); ++Func) { 1358 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1359 if (AllowExplicit || !Conv->isExplicit()) 1360 AddConversionCandidate(Conv, From, ToType, CandidateSet); 1361 } 1362 } 1363 } 1364 1365 OverloadCandidateSet::iterator Best; 1366 switch (BestViableFunction(CandidateSet, Best)) { 1367 case OR_Success: 1368 // Record the standard conversion we used and the conversion function. 1369 if (CXXConstructorDecl *Constructor 1370 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 1371 // C++ [over.ics.user]p1: 1372 // If the user-defined conversion is specified by a 1373 // constructor (12.3.1), the initial standard conversion 1374 // sequence converts the source type to the type required by 1375 // the argument of the constructor. 1376 // 1377 // FIXME: What about ellipsis conversions? 1378 QualType ThisType = Constructor->getThisType(Context); 1379 User.Before = Best->Conversions[0].Standard; 1380 User.ConversionFunction = Constructor; 1381 User.After.setAsIdentityConversion(); 1382 User.After.FromTypePtr 1383 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 1384 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 1385 return true; 1386 } else if (CXXConversionDecl *Conversion 1387 = dyn_cast<CXXConversionDecl>(Best->Function)) { 1388 // C++ [over.ics.user]p1: 1389 // 1390 // [...] If the user-defined conversion is specified by a 1391 // conversion function (12.3.2), the initial standard 1392 // conversion sequence converts the source type to the 1393 // implicit object parameter of the conversion function. 1394 User.Before = Best->Conversions[0].Standard; 1395 User.ConversionFunction = Conversion; 1396 1397 // C++ [over.ics.user]p2: 1398 // The second standard conversion sequence converts the 1399 // result of the user-defined conversion to the target type 1400 // for the sequence. Since an implicit conversion sequence 1401 // is an initialization, the special rules for 1402 // initialization by user-defined conversion apply when 1403 // selecting the best user-defined conversion for a 1404 // user-defined conversion sequence (see 13.3.3 and 1405 // 13.3.3.1). 1406 User.After = Best->FinalConversion; 1407 return true; 1408 } else { 1409 assert(false && "Not a constructor or conversion function?"); 1410 return false; 1411 } 1412 1413 case OR_No_Viable_Function: 1414 case OR_Deleted: 1415 // No conversion here! We're done. 1416 return false; 1417 1418 case OR_Ambiguous: 1419 // FIXME: See C++ [over.best.ics]p10 for the handling of 1420 // ambiguous conversion sequences. 1421 return false; 1422 } 1423 1424 return false; 1425} 1426 1427/// CompareImplicitConversionSequences - Compare two implicit 1428/// conversion sequences to determine whether one is better than the 1429/// other or if they are indistinguishable (C++ 13.3.3.2). 1430ImplicitConversionSequence::CompareKind 1431Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 1432 const ImplicitConversionSequence& ICS2) 1433{ 1434 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 1435 // conversion sequences (as defined in 13.3.3.1) 1436 // -- a standard conversion sequence (13.3.3.1.1) is a better 1437 // conversion sequence than a user-defined conversion sequence or 1438 // an ellipsis conversion sequence, and 1439 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 1440 // conversion sequence than an ellipsis conversion sequence 1441 // (13.3.3.1.3). 1442 // 1443 if (ICS1.ConversionKind < ICS2.ConversionKind) 1444 return ImplicitConversionSequence::Better; 1445 else if (ICS2.ConversionKind < ICS1.ConversionKind) 1446 return ImplicitConversionSequence::Worse; 1447 1448 // Two implicit conversion sequences of the same form are 1449 // indistinguishable conversion sequences unless one of the 1450 // following rules apply: (C++ 13.3.3.2p3): 1451 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 1452 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 1453 else if (ICS1.ConversionKind == 1454 ImplicitConversionSequence::UserDefinedConversion) { 1455 // User-defined conversion sequence U1 is a better conversion 1456 // sequence than another user-defined conversion sequence U2 if 1457 // they contain the same user-defined conversion function or 1458 // constructor and if the second standard conversion sequence of 1459 // U1 is better than the second standard conversion sequence of 1460 // U2 (C++ 13.3.3.2p3). 1461 if (ICS1.UserDefined.ConversionFunction == 1462 ICS2.UserDefined.ConversionFunction) 1463 return CompareStandardConversionSequences(ICS1.UserDefined.After, 1464 ICS2.UserDefined.After); 1465 } 1466 1467 return ImplicitConversionSequence::Indistinguishable; 1468} 1469 1470/// CompareStandardConversionSequences - Compare two standard 1471/// conversion sequences to determine whether one is better than the 1472/// other or if they are indistinguishable (C++ 13.3.3.2p3). 1473ImplicitConversionSequence::CompareKind 1474Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 1475 const StandardConversionSequence& SCS2) 1476{ 1477 // Standard conversion sequence S1 is a better conversion sequence 1478 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 1479 1480 // -- S1 is a proper subsequence of S2 (comparing the conversion 1481 // sequences in the canonical form defined by 13.3.3.1.1, 1482 // excluding any Lvalue Transformation; the identity conversion 1483 // sequence is considered to be a subsequence of any 1484 // non-identity conversion sequence) or, if not that, 1485 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 1486 // Neither is a proper subsequence of the other. Do nothing. 1487 ; 1488 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1489 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1490 (SCS1.Second == ICK_Identity && 1491 SCS1.Third == ICK_Identity)) 1492 // SCS1 is a proper subsequence of SCS2. 1493 return ImplicitConversionSequence::Better; 1494 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1495 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1496 (SCS2.Second == ICK_Identity && 1497 SCS2.Third == ICK_Identity)) 1498 // SCS2 is a proper subsequence of SCS1. 1499 return ImplicitConversionSequence::Worse; 1500 1501 // -- the rank of S1 is better than the rank of S2 (by the rules 1502 // defined below), or, if not that, 1503 ImplicitConversionRank Rank1 = SCS1.getRank(); 1504 ImplicitConversionRank Rank2 = SCS2.getRank(); 1505 if (Rank1 < Rank2) 1506 return ImplicitConversionSequence::Better; 1507 else if (Rank2 < Rank1) 1508 return ImplicitConversionSequence::Worse; 1509 1510 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1511 // are indistinguishable unless one of the following rules 1512 // applies: 1513 1514 // A conversion that is not a conversion of a pointer, or 1515 // pointer to member, to bool is better than another conversion 1516 // that is such a conversion. 1517 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1518 return SCS2.isPointerConversionToBool() 1519 ? ImplicitConversionSequence::Better 1520 : ImplicitConversionSequence::Worse; 1521 1522 // C++ [over.ics.rank]p4b2: 1523 // 1524 // If class B is derived directly or indirectly from class A, 1525 // conversion of B* to A* is better than conversion of B* to 1526 // void*, and conversion of A* to void* is better than conversion 1527 // of B* to void*. 1528 bool SCS1ConvertsToVoid 1529 = SCS1.isPointerConversionToVoidPointer(Context); 1530 bool SCS2ConvertsToVoid 1531 = SCS2.isPointerConversionToVoidPointer(Context); 1532 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1533 // Exactly one of the conversion sequences is a conversion to 1534 // a void pointer; it's the worse conversion. 1535 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1536 : ImplicitConversionSequence::Worse; 1537 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1538 // Neither conversion sequence converts to a void pointer; compare 1539 // their derived-to-base conversions. 1540 if (ImplicitConversionSequence::CompareKind DerivedCK 1541 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1542 return DerivedCK; 1543 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1544 // Both conversion sequences are conversions to void 1545 // pointers. Compare the source types to determine if there's an 1546 // inheritance relationship in their sources. 1547 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1548 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1549 1550 // Adjust the types we're converting from via the array-to-pointer 1551 // conversion, if we need to. 1552 if (SCS1.First == ICK_Array_To_Pointer) 1553 FromType1 = Context.getArrayDecayedType(FromType1); 1554 if (SCS2.First == ICK_Array_To_Pointer) 1555 FromType2 = Context.getArrayDecayedType(FromType2); 1556 1557 QualType FromPointee1 1558 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1559 QualType FromPointee2 1560 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1561 1562 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1563 return ImplicitConversionSequence::Better; 1564 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1565 return ImplicitConversionSequence::Worse; 1566 1567 // Objective-C++: If one interface is more specific than the 1568 // other, it is the better one. 1569 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1570 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1571 if (FromIface1 && FromIface1) { 1572 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1573 return ImplicitConversionSequence::Better; 1574 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1575 return ImplicitConversionSequence::Worse; 1576 } 1577 } 1578 1579 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1580 // bullet 3). 1581 if (ImplicitConversionSequence::CompareKind QualCK 1582 = CompareQualificationConversions(SCS1, SCS2)) 1583 return QualCK; 1584 1585 // C++ [over.ics.rank]p3b4: 1586 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1587 // which the references refer are the same type except for 1588 // top-level cv-qualifiers, and the type to which the reference 1589 // initialized by S2 refers is more cv-qualified than the type 1590 // to which the reference initialized by S1 refers. 1591 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1592 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1593 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1594 T1 = Context.getCanonicalType(T1); 1595 T2 = Context.getCanonicalType(T2); 1596 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1597 if (T2.isMoreQualifiedThan(T1)) 1598 return ImplicitConversionSequence::Better; 1599 else if (T1.isMoreQualifiedThan(T2)) 1600 return ImplicitConversionSequence::Worse; 1601 } 1602 } 1603 1604 return ImplicitConversionSequence::Indistinguishable; 1605} 1606 1607/// CompareQualificationConversions - Compares two standard conversion 1608/// sequences to determine whether they can be ranked based on their 1609/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1610ImplicitConversionSequence::CompareKind 1611Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1612 const StandardConversionSequence& SCS2) 1613{ 1614 // C++ 13.3.3.2p3: 1615 // -- S1 and S2 differ only in their qualification conversion and 1616 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1617 // cv-qualification signature of type T1 is a proper subset of 1618 // the cv-qualification signature of type T2, and S1 is not the 1619 // deprecated string literal array-to-pointer conversion (4.2). 1620 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1621 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1622 return ImplicitConversionSequence::Indistinguishable; 1623 1624 // FIXME: the example in the standard doesn't use a qualification 1625 // conversion (!) 1626 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1627 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1628 T1 = Context.getCanonicalType(T1); 1629 T2 = Context.getCanonicalType(T2); 1630 1631 // If the types are the same, we won't learn anything by unwrapped 1632 // them. 1633 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1634 return ImplicitConversionSequence::Indistinguishable; 1635 1636 ImplicitConversionSequence::CompareKind Result 1637 = ImplicitConversionSequence::Indistinguishable; 1638 while (UnwrapSimilarPointerTypes(T1, T2)) { 1639 // Within each iteration of the loop, we check the qualifiers to 1640 // determine if this still looks like a qualification 1641 // conversion. Then, if all is well, we unwrap one more level of 1642 // pointers or pointers-to-members and do it all again 1643 // until there are no more pointers or pointers-to-members left 1644 // to unwrap. This essentially mimics what 1645 // IsQualificationConversion does, but here we're checking for a 1646 // strict subset of qualifiers. 1647 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1648 // The qualifiers are the same, so this doesn't tell us anything 1649 // about how the sequences rank. 1650 ; 1651 else if (T2.isMoreQualifiedThan(T1)) { 1652 // T1 has fewer qualifiers, so it could be the better sequence. 1653 if (Result == ImplicitConversionSequence::Worse) 1654 // Neither has qualifiers that are a subset of the other's 1655 // qualifiers. 1656 return ImplicitConversionSequence::Indistinguishable; 1657 1658 Result = ImplicitConversionSequence::Better; 1659 } else if (T1.isMoreQualifiedThan(T2)) { 1660 // T2 has fewer qualifiers, so it could be the better sequence. 1661 if (Result == ImplicitConversionSequence::Better) 1662 // Neither has qualifiers that are a subset of the other's 1663 // qualifiers. 1664 return ImplicitConversionSequence::Indistinguishable; 1665 1666 Result = ImplicitConversionSequence::Worse; 1667 } else { 1668 // Qualifiers are disjoint. 1669 return ImplicitConversionSequence::Indistinguishable; 1670 } 1671 1672 // If the types after this point are equivalent, we're done. 1673 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1674 break; 1675 } 1676 1677 // Check that the winning standard conversion sequence isn't using 1678 // the deprecated string literal array to pointer conversion. 1679 switch (Result) { 1680 case ImplicitConversionSequence::Better: 1681 if (SCS1.Deprecated) 1682 Result = ImplicitConversionSequence::Indistinguishable; 1683 break; 1684 1685 case ImplicitConversionSequence::Indistinguishable: 1686 break; 1687 1688 case ImplicitConversionSequence::Worse: 1689 if (SCS2.Deprecated) 1690 Result = ImplicitConversionSequence::Indistinguishable; 1691 break; 1692 } 1693 1694 return Result; 1695} 1696 1697/// CompareDerivedToBaseConversions - Compares two standard conversion 1698/// sequences to determine whether they can be ranked based on their 1699/// various kinds of derived-to-base conversions (C++ 1700/// [over.ics.rank]p4b3). As part of these checks, we also look at 1701/// conversions between Objective-C interface types. 1702ImplicitConversionSequence::CompareKind 1703Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1704 const StandardConversionSequence& SCS2) { 1705 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1706 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1707 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1708 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1709 1710 // Adjust the types we're converting from via the array-to-pointer 1711 // conversion, if we need to. 1712 if (SCS1.First == ICK_Array_To_Pointer) 1713 FromType1 = Context.getArrayDecayedType(FromType1); 1714 if (SCS2.First == ICK_Array_To_Pointer) 1715 FromType2 = Context.getArrayDecayedType(FromType2); 1716 1717 // Canonicalize all of the types. 1718 FromType1 = Context.getCanonicalType(FromType1); 1719 ToType1 = Context.getCanonicalType(ToType1); 1720 FromType2 = Context.getCanonicalType(FromType2); 1721 ToType2 = Context.getCanonicalType(ToType2); 1722 1723 // C++ [over.ics.rank]p4b3: 1724 // 1725 // If class B is derived directly or indirectly from class A and 1726 // class C is derived directly or indirectly from B, 1727 // 1728 // For Objective-C, we let A, B, and C also be Objective-C 1729 // interfaces. 1730 1731 // Compare based on pointer conversions. 1732 if (SCS1.Second == ICK_Pointer_Conversion && 1733 SCS2.Second == ICK_Pointer_Conversion && 1734 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 1735 FromType1->isPointerType() && FromType2->isPointerType() && 1736 ToType1->isPointerType() && ToType2->isPointerType()) { 1737 QualType FromPointee1 1738 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1739 QualType ToPointee1 1740 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1741 QualType FromPointee2 1742 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1743 QualType ToPointee2 1744 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1745 1746 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1747 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1748 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType(); 1749 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType(); 1750 1751 // -- conversion of C* to B* is better than conversion of C* to A*, 1752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1753 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1754 return ImplicitConversionSequence::Better; 1755 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1756 return ImplicitConversionSequence::Worse; 1757 1758 if (ToIface1 && ToIface2) { 1759 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 1760 return ImplicitConversionSequence::Better; 1761 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 1762 return ImplicitConversionSequence::Worse; 1763 } 1764 } 1765 1766 // -- conversion of B* to A* is better than conversion of C* to A*, 1767 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1768 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1769 return ImplicitConversionSequence::Better; 1770 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1771 return ImplicitConversionSequence::Worse; 1772 1773 if (FromIface1 && FromIface2) { 1774 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1775 return ImplicitConversionSequence::Better; 1776 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1777 return ImplicitConversionSequence::Worse; 1778 } 1779 } 1780 } 1781 1782 // Compare based on reference bindings. 1783 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1784 SCS1.Second == ICK_Derived_To_Base) { 1785 // -- binding of an expression of type C to a reference of type 1786 // B& is better than binding an expression of type C to a 1787 // reference of type A&, 1788 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1789 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1790 if (IsDerivedFrom(ToType1, ToType2)) 1791 return ImplicitConversionSequence::Better; 1792 else if (IsDerivedFrom(ToType2, ToType1)) 1793 return ImplicitConversionSequence::Worse; 1794 } 1795 1796 // -- binding of an expression of type B to a reference of type 1797 // A& is better than binding an expression of type C to a 1798 // reference of type A&, 1799 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1800 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1801 if (IsDerivedFrom(FromType2, FromType1)) 1802 return ImplicitConversionSequence::Better; 1803 else if (IsDerivedFrom(FromType1, FromType2)) 1804 return ImplicitConversionSequence::Worse; 1805 } 1806 } 1807 1808 1809 // FIXME: conversion of A::* to B::* is better than conversion of 1810 // A::* to C::*, 1811 1812 // FIXME: conversion of B::* to C::* is better than conversion of 1813 // A::* to C::*, and 1814 1815 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1816 SCS1.Second == ICK_Derived_To_Base) { 1817 // -- conversion of C to B is better than conversion of C to A, 1818 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1819 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1820 if (IsDerivedFrom(ToType1, ToType2)) 1821 return ImplicitConversionSequence::Better; 1822 else if (IsDerivedFrom(ToType2, ToType1)) 1823 return ImplicitConversionSequence::Worse; 1824 } 1825 1826 // -- conversion of B to A is better than conversion of C to A. 1827 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1828 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1829 if (IsDerivedFrom(FromType2, FromType1)) 1830 return ImplicitConversionSequence::Better; 1831 else if (IsDerivedFrom(FromType1, FromType2)) 1832 return ImplicitConversionSequence::Worse; 1833 } 1834 } 1835 1836 return ImplicitConversionSequence::Indistinguishable; 1837} 1838 1839/// TryCopyInitialization - Try to copy-initialize a value of type 1840/// ToType from the expression From. Return the implicit conversion 1841/// sequence required to pass this argument, which may be a bad 1842/// conversion sequence (meaning that the argument cannot be passed to 1843/// a parameter of this type). If @p SuppressUserConversions, then we 1844/// do not permit any user-defined conversion sequences. 1845ImplicitConversionSequence 1846Sema::TryCopyInitialization(Expr *From, QualType ToType, 1847 bool SuppressUserConversions) { 1848 if (ToType->isReferenceType()) { 1849 ImplicitConversionSequence ICS; 1850 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1851 return ICS; 1852 } else { 1853 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1854 } 1855} 1856 1857/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1858/// type ToType. Returns true (and emits a diagnostic) if there was 1859/// an error, returns false if the initialization succeeded. 1860bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1861 const char* Flavor) { 1862 if (!getLangOptions().CPlusPlus) { 1863 // In C, argument passing is the same as performing an assignment. 1864 QualType FromType = From->getType(); 1865 AssignConvertType ConvTy = 1866 CheckSingleAssignmentConstraints(ToType, From); 1867 1868 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1869 FromType, From, Flavor); 1870 } 1871 1872 if (ToType->isReferenceType()) 1873 return CheckReferenceInit(From, ToType); 1874 1875 if (!PerformImplicitConversion(From, ToType, Flavor)) 1876 return false; 1877 1878 return Diag(From->getSourceRange().getBegin(), 1879 diag::err_typecheck_convert_incompatible) 1880 << ToType << From->getType() << Flavor << From->getSourceRange(); 1881} 1882 1883/// TryObjectArgumentInitialization - Try to initialize the object 1884/// parameter of the given member function (@c Method) from the 1885/// expression @p From. 1886ImplicitConversionSequence 1887Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) { 1888 QualType ClassType = Context.getTypeDeclType(Method->getParent()); 1889 unsigned MethodQuals = Method->getTypeQualifiers(); 1890 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals); 1891 1892 // Set up the conversion sequence as a "bad" conversion, to allow us 1893 // to exit early. 1894 ImplicitConversionSequence ICS; 1895 ICS.Standard.setAsIdentityConversion(); 1896 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1897 1898 // We need to have an object of class type. 1899 QualType FromType = From->getType(); 1900 if (!FromType->isRecordType()) 1901 return ICS; 1902 1903 // The implicit object parmeter is has the type "reference to cv X", 1904 // where X is the class of which the function is a member 1905 // (C++ [over.match.funcs]p4). However, when finding an implicit 1906 // conversion sequence for the argument, we are not allowed to 1907 // create temporaries or perform user-defined conversions 1908 // (C++ [over.match.funcs]p5). We perform a simplified version of 1909 // reference binding here, that allows class rvalues to bind to 1910 // non-constant references. 1911 1912 // First check the qualifiers. We don't care about lvalue-vs-rvalue 1913 // with the implicit object parameter (C++ [over.match.funcs]p5). 1914 QualType FromTypeCanon = Context.getCanonicalType(FromType); 1915 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() && 1916 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType)) 1917 return ICS; 1918 1919 // Check that we have either the same type or a derived type. It 1920 // affects the conversion rank. 1921 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 1922 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType()) 1923 ICS.Standard.Second = ICK_Identity; 1924 else if (IsDerivedFrom(FromType, ClassType)) 1925 ICS.Standard.Second = ICK_Derived_To_Base; 1926 else 1927 return ICS; 1928 1929 // Success. Mark this as a reference binding. 1930 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1931 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr(); 1932 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr(); 1933 ICS.Standard.ReferenceBinding = true; 1934 ICS.Standard.DirectBinding = true; 1935 return ICS; 1936} 1937 1938/// PerformObjectArgumentInitialization - Perform initialization of 1939/// the implicit object parameter for the given Method with the given 1940/// expression. 1941bool 1942Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) { 1943 QualType ImplicitParamType 1944 = Method->getThisType(Context)->getAsPointerType()->getPointeeType(); 1945 ImplicitConversionSequence ICS 1946 = TryObjectArgumentInitialization(From, Method); 1947 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) 1948 return Diag(From->getSourceRange().getBegin(), 1949 diag::err_implicit_object_parameter_init) 1950 << ImplicitParamType << From->getType() << From->getSourceRange(); 1951 1952 if (ICS.Standard.Second == ICK_Derived_To_Base && 1953 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType, 1954 From->getSourceRange().getBegin(), 1955 From->getSourceRange())) 1956 return true; 1957 1958 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true); 1959 return false; 1960} 1961 1962/// TryContextuallyConvertToBool - Attempt to contextually convert the 1963/// expression From to bool (C++0x [conv]p3). 1964ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) { 1965 return TryImplicitConversion(From, Context.BoolTy, false, true); 1966} 1967 1968/// PerformContextuallyConvertToBool - Perform a contextual conversion 1969/// of the expression From to bool (C++0x [conv]p3). 1970bool Sema::PerformContextuallyConvertToBool(Expr *&From) { 1971 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From); 1972 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting")) 1973 return false; 1974 1975 return Diag(From->getSourceRange().getBegin(), 1976 diag::err_typecheck_bool_condition) 1977 << From->getType() << From->getSourceRange(); 1978} 1979 1980/// AddOverloadCandidate - Adds the given function to the set of 1981/// candidate functions, using the given function call arguments. If 1982/// @p SuppressUserConversions, then don't allow user-defined 1983/// conversions via constructors or conversion operators. 1984void 1985Sema::AddOverloadCandidate(FunctionDecl *Function, 1986 Expr **Args, unsigned NumArgs, 1987 OverloadCandidateSet& CandidateSet, 1988 bool SuppressUserConversions) 1989{ 1990 const FunctionProtoType* Proto 1991 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType()); 1992 assert(Proto && "Functions without a prototype cannot be overloaded"); 1993 assert(!isa<CXXConversionDecl>(Function) && 1994 "Use AddConversionCandidate for conversion functions"); 1995 1996 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 1997 // If we get here, it's because we're calling a member function 1998 // that is named without a member access expression (e.g., 1999 // "this->f") that was either written explicitly or created 2000 // implicitly. This can happen with a qualified call to a member 2001 // function, e.g., X::f(). We use a NULL object as the implied 2002 // object argument (C++ [over.call.func]p3). 2003 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet, 2004 SuppressUserConversions); 2005 return; 2006 } 2007 2008 2009 // Add this candidate 2010 CandidateSet.push_back(OverloadCandidate()); 2011 OverloadCandidate& Candidate = CandidateSet.back(); 2012 Candidate.Function = Function; 2013 Candidate.Viable = true; 2014 Candidate.IsSurrogate = false; 2015 Candidate.IgnoreObjectArgument = false; 2016 2017 unsigned NumArgsInProto = Proto->getNumArgs(); 2018 2019 // (C++ 13.3.2p2): A candidate function having fewer than m 2020 // parameters is viable only if it has an ellipsis in its parameter 2021 // list (8.3.5). 2022 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2023 Candidate.Viable = false; 2024 return; 2025 } 2026 2027 // (C++ 13.3.2p2): A candidate function having more than m parameters 2028 // is viable only if the (m+1)st parameter has a default argument 2029 // (8.3.6). For the purposes of overload resolution, the 2030 // parameter list is truncated on the right, so that there are 2031 // exactly m parameters. 2032 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 2033 if (NumArgs < MinRequiredArgs) { 2034 // Not enough arguments. 2035 Candidate.Viable = false; 2036 return; 2037 } 2038 2039 // Determine the implicit conversion sequences for each of the 2040 // arguments. 2041 Candidate.Conversions.resize(NumArgs); 2042 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2043 if (ArgIdx < NumArgsInProto) { 2044 // (C++ 13.3.2p3): for F to be a viable function, there shall 2045 // exist for each argument an implicit conversion sequence 2046 // (13.3.3.1) that converts that argument to the corresponding 2047 // parameter of F. 2048 QualType ParamType = Proto->getArgType(ArgIdx); 2049 Candidate.Conversions[ArgIdx] 2050 = TryCopyInitialization(Args[ArgIdx], ParamType, 2051 SuppressUserConversions); 2052 if (Candidate.Conversions[ArgIdx].ConversionKind 2053 == ImplicitConversionSequence::BadConversion) { 2054 Candidate.Viable = false; 2055 break; 2056 } 2057 } else { 2058 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2059 // argument for which there is no corresponding parameter is 2060 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2061 Candidate.Conversions[ArgIdx].ConversionKind 2062 = ImplicitConversionSequence::EllipsisConversion; 2063 } 2064 } 2065} 2066 2067/// AddMethodCandidate - Adds the given C++ member function to the set 2068/// of candidate functions, using the given function call arguments 2069/// and the object argument (@c Object). For example, in a call 2070/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 2071/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 2072/// allow user-defined conversions via constructors or conversion 2073/// operators. 2074void 2075Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object, 2076 Expr **Args, unsigned NumArgs, 2077 OverloadCandidateSet& CandidateSet, 2078 bool SuppressUserConversions) 2079{ 2080 const FunctionProtoType* Proto 2081 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType()); 2082 assert(Proto && "Methods without a prototype cannot be overloaded"); 2083 assert(!isa<CXXConversionDecl>(Method) && 2084 "Use AddConversionCandidate for conversion functions"); 2085 2086 // Add this candidate 2087 CandidateSet.push_back(OverloadCandidate()); 2088 OverloadCandidate& Candidate = CandidateSet.back(); 2089 Candidate.Function = Method; 2090 Candidate.IsSurrogate = false; 2091 Candidate.IgnoreObjectArgument = false; 2092 2093 unsigned NumArgsInProto = Proto->getNumArgs(); 2094 2095 // (C++ 13.3.2p2): A candidate function having fewer than m 2096 // parameters is viable only if it has an ellipsis in its parameter 2097 // list (8.3.5). 2098 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2099 Candidate.Viable = false; 2100 return; 2101 } 2102 2103 // (C++ 13.3.2p2): A candidate function having more than m parameters 2104 // is viable only if the (m+1)st parameter has a default argument 2105 // (8.3.6). For the purposes of overload resolution, the 2106 // parameter list is truncated on the right, so that there are 2107 // exactly m parameters. 2108 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 2109 if (NumArgs < MinRequiredArgs) { 2110 // Not enough arguments. 2111 Candidate.Viable = false; 2112 return; 2113 } 2114 2115 Candidate.Viable = true; 2116 Candidate.Conversions.resize(NumArgs + 1); 2117 2118 if (Method->isStatic() || !Object) 2119 // The implicit object argument is ignored. 2120 Candidate.IgnoreObjectArgument = true; 2121 else { 2122 // Determine the implicit conversion sequence for the object 2123 // parameter. 2124 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method); 2125 if (Candidate.Conversions[0].ConversionKind 2126 == ImplicitConversionSequence::BadConversion) { 2127 Candidate.Viable = false; 2128 return; 2129 } 2130 } 2131 2132 // Determine the implicit conversion sequences for each of the 2133 // arguments. 2134 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2135 if (ArgIdx < NumArgsInProto) { 2136 // (C++ 13.3.2p3): for F to be a viable function, there shall 2137 // exist for each argument an implicit conversion sequence 2138 // (13.3.3.1) that converts that argument to the corresponding 2139 // parameter of F. 2140 QualType ParamType = Proto->getArgType(ArgIdx); 2141 Candidate.Conversions[ArgIdx + 1] 2142 = TryCopyInitialization(Args[ArgIdx], ParamType, 2143 SuppressUserConversions); 2144 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 2145 == ImplicitConversionSequence::BadConversion) { 2146 Candidate.Viable = false; 2147 break; 2148 } 2149 } else { 2150 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2151 // argument for which there is no corresponding parameter is 2152 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2153 Candidate.Conversions[ArgIdx + 1].ConversionKind 2154 = ImplicitConversionSequence::EllipsisConversion; 2155 } 2156 } 2157} 2158 2159/// AddConversionCandidate - Add a C++ conversion function as a 2160/// candidate in the candidate set (C++ [over.match.conv], 2161/// C++ [over.match.copy]). From is the expression we're converting from, 2162/// and ToType is the type that we're eventually trying to convert to 2163/// (which may or may not be the same type as the type that the 2164/// conversion function produces). 2165void 2166Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 2167 Expr *From, QualType ToType, 2168 OverloadCandidateSet& CandidateSet) { 2169 // Add this candidate 2170 CandidateSet.push_back(OverloadCandidate()); 2171 OverloadCandidate& Candidate = CandidateSet.back(); 2172 Candidate.Function = Conversion; 2173 Candidate.IsSurrogate = false; 2174 Candidate.IgnoreObjectArgument = false; 2175 Candidate.FinalConversion.setAsIdentityConversion(); 2176 Candidate.FinalConversion.FromTypePtr 2177 = Conversion->getConversionType().getAsOpaquePtr(); 2178 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr(); 2179 2180 // Determine the implicit conversion sequence for the implicit 2181 // object parameter. 2182 Candidate.Viable = true; 2183 Candidate.Conversions.resize(1); 2184 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion); 2185 2186 if (Candidate.Conversions[0].ConversionKind 2187 == ImplicitConversionSequence::BadConversion) { 2188 Candidate.Viable = false; 2189 return; 2190 } 2191 2192 // To determine what the conversion from the result of calling the 2193 // conversion function to the type we're eventually trying to 2194 // convert to (ToType), we need to synthesize a call to the 2195 // conversion function and attempt copy initialization from it. This 2196 // makes sure that we get the right semantics with respect to 2197 // lvalues/rvalues and the type. Fortunately, we can allocate this 2198 // call on the stack and we don't need its arguments to be 2199 // well-formed. 2200 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 2201 SourceLocation()); 2202 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 2203 &ConversionRef, false); 2204 2205 // Note that it is safe to allocate CallExpr on the stack here because 2206 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 2207 // allocator). 2208 CallExpr Call(Context, &ConversionFn, 0, 0, 2209 Conversion->getConversionType().getNonReferenceType(), 2210 SourceLocation()); 2211 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true); 2212 switch (ICS.ConversionKind) { 2213 case ImplicitConversionSequence::StandardConversion: 2214 Candidate.FinalConversion = ICS.Standard; 2215 break; 2216 2217 case ImplicitConversionSequence::BadConversion: 2218 Candidate.Viable = false; 2219 break; 2220 2221 default: 2222 assert(false && 2223 "Can only end up with a standard conversion sequence or failure"); 2224 } 2225} 2226 2227/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 2228/// converts the given @c Object to a function pointer via the 2229/// conversion function @c Conversion, and then attempts to call it 2230/// with the given arguments (C++ [over.call.object]p2-4). Proto is 2231/// the type of function that we'll eventually be calling. 2232void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 2233 const FunctionProtoType *Proto, 2234 Expr *Object, Expr **Args, unsigned NumArgs, 2235 OverloadCandidateSet& CandidateSet) { 2236 CandidateSet.push_back(OverloadCandidate()); 2237 OverloadCandidate& Candidate = CandidateSet.back(); 2238 Candidate.Function = 0; 2239 Candidate.Surrogate = Conversion; 2240 Candidate.Viable = true; 2241 Candidate.IsSurrogate = true; 2242 Candidate.IgnoreObjectArgument = false; 2243 Candidate.Conversions.resize(NumArgs + 1); 2244 2245 // Determine the implicit conversion sequence for the implicit 2246 // object parameter. 2247 ImplicitConversionSequence ObjectInit 2248 = TryObjectArgumentInitialization(Object, Conversion); 2249 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) { 2250 Candidate.Viable = false; 2251 return; 2252 } 2253 2254 // The first conversion is actually a user-defined conversion whose 2255 // first conversion is ObjectInit's standard conversion (which is 2256 // effectively a reference binding). Record it as such. 2257 Candidate.Conversions[0].ConversionKind 2258 = ImplicitConversionSequence::UserDefinedConversion; 2259 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 2260 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 2261 Candidate.Conversions[0].UserDefined.After 2262 = Candidate.Conversions[0].UserDefined.Before; 2263 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 2264 2265 // Find the 2266 unsigned NumArgsInProto = Proto->getNumArgs(); 2267 2268 // (C++ 13.3.2p2): A candidate function having fewer than m 2269 // parameters is viable only if it has an ellipsis in its parameter 2270 // list (8.3.5). 2271 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2272 Candidate.Viable = false; 2273 return; 2274 } 2275 2276 // Function types don't have any default arguments, so just check if 2277 // we have enough arguments. 2278 if (NumArgs < NumArgsInProto) { 2279 // Not enough arguments. 2280 Candidate.Viable = false; 2281 return; 2282 } 2283 2284 // Determine the implicit conversion sequences for each of the 2285 // arguments. 2286 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2287 if (ArgIdx < NumArgsInProto) { 2288 // (C++ 13.3.2p3): for F to be a viable function, there shall 2289 // exist for each argument an implicit conversion sequence 2290 // (13.3.3.1) that converts that argument to the corresponding 2291 // parameter of F. 2292 QualType ParamType = Proto->getArgType(ArgIdx); 2293 Candidate.Conversions[ArgIdx + 1] 2294 = TryCopyInitialization(Args[ArgIdx], ParamType, 2295 /*SuppressUserConversions=*/false); 2296 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 2297 == ImplicitConversionSequence::BadConversion) { 2298 Candidate.Viable = false; 2299 break; 2300 } 2301 } else { 2302 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2303 // argument for which there is no corresponding parameter is 2304 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2305 Candidate.Conversions[ArgIdx + 1].ConversionKind 2306 = ImplicitConversionSequence::EllipsisConversion; 2307 } 2308 } 2309} 2310 2311/// AddOperatorCandidates - Add the overloaded operator candidates for 2312/// the operator Op that was used in an operator expression such as "x 2313/// Op y". S is the scope in which the expression occurred (used for 2314/// name lookup of the operator), Args/NumArgs provides the operator 2315/// arguments, and CandidateSet will store the added overload 2316/// candidates. (C++ [over.match.oper]). 2317bool Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 2318 SourceLocation OpLoc, 2319 Expr **Args, unsigned NumArgs, 2320 OverloadCandidateSet& CandidateSet, 2321 SourceRange OpRange) { 2322 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2323 2324 // C++ [over.match.oper]p3: 2325 // For a unary operator @ with an operand of a type whose 2326 // cv-unqualified version is T1, and for a binary operator @ with 2327 // a left operand of a type whose cv-unqualified version is T1 and 2328 // a right operand of a type whose cv-unqualified version is T2, 2329 // three sets of candidate functions, designated member 2330 // candidates, non-member candidates and built-in candidates, are 2331 // constructed as follows: 2332 QualType T1 = Args[0]->getType(); 2333 QualType T2; 2334 if (NumArgs > 1) 2335 T2 = Args[1]->getType(); 2336 2337 // -- If T1 is a class type, the set of member candidates is the 2338 // result of the qualified lookup of T1::operator@ 2339 // (13.3.1.1.1); otherwise, the set of member candidates is 2340 // empty. 2341 if (const RecordType *T1Rec = T1->getAsRecordType()) { 2342 DeclContext::lookup_const_iterator Oper, OperEnd; 2343 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName); 2344 Oper != OperEnd; ++Oper) 2345 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0], 2346 Args+1, NumArgs - 1, CandidateSet, 2347 /*SuppressUserConversions=*/false); 2348 } 2349 2350 FunctionSet Functions; 2351 2352 // -- The set of non-member candidates is the result of the 2353 // unqualified lookup of operator@ in the context of the 2354 // expression according to the usual rules for name lookup in 2355 // unqualified function calls (3.4.2) except that all member 2356 // functions are ignored. However, if no operand has a class 2357 // type, only those non-member functions in the lookup set 2358 // that have a first parameter of type T1 or “reference to 2359 // (possibly cv-qualified) T1”, when T1 is an enumeration 2360 // type, or (if there is a right operand) a second parameter 2361 // of type T2 or “reference to (possibly cv-qualified) T2”, 2362 // when T2 is an enumeration type, are candidate functions. 2363 LookupOverloadedOperatorName(Op, S, T1, T2, Functions); 2364 2365 // Since the set of non-member candidates corresponds to 2366 // *unqualified* lookup of the operator name, we also perform 2367 // argument-dependent lookup (C++ [basic.lookup.argdep]). 2368 ArgumentDependentLookup(OpName, Args, NumArgs, Functions); 2369 2370 // Add all of the functions found via operator name lookup and 2371 // argument-dependent lookup to the candidate set. 2372 for (FunctionSet::iterator Func = Functions.begin(), 2373 FuncEnd = Functions.end(); 2374 Func != FuncEnd; ++Func) 2375 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet); 2376 2377 // Add builtin overload candidates (C++ [over.built]). 2378 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet); 2379 2380 return false; 2381} 2382 2383/// AddBuiltinCandidate - Add a candidate for a built-in 2384/// operator. ResultTy and ParamTys are the result and parameter types 2385/// of the built-in candidate, respectively. Args and NumArgs are the 2386/// arguments being passed to the candidate. IsAssignmentOperator 2387/// should be true when this built-in candidate is an assignment 2388/// operator. NumContextualBoolArguments is the number of arguments 2389/// (at the beginning of the argument list) that will be contextually 2390/// converted to bool. 2391void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2392 Expr **Args, unsigned NumArgs, 2393 OverloadCandidateSet& CandidateSet, 2394 bool IsAssignmentOperator, 2395 unsigned NumContextualBoolArguments) { 2396 // Add this candidate 2397 CandidateSet.push_back(OverloadCandidate()); 2398 OverloadCandidate& Candidate = CandidateSet.back(); 2399 Candidate.Function = 0; 2400 Candidate.IsSurrogate = false; 2401 Candidate.IgnoreObjectArgument = false; 2402 Candidate.BuiltinTypes.ResultTy = ResultTy; 2403 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2404 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 2405 2406 // Determine the implicit conversion sequences for each of the 2407 // arguments. 2408 Candidate.Viable = true; 2409 Candidate.Conversions.resize(NumArgs); 2410 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2411 // C++ [over.match.oper]p4: 2412 // For the built-in assignment operators, conversions of the 2413 // left operand are restricted as follows: 2414 // -- no temporaries are introduced to hold the left operand, and 2415 // -- no user-defined conversions are applied to the left 2416 // operand to achieve a type match with the left-most 2417 // parameter of a built-in candidate. 2418 // 2419 // We block these conversions by turning off user-defined 2420 // conversions, since that is the only way that initialization of 2421 // a reference to a non-class type can occur from something that 2422 // is not of the same type. 2423 if (ArgIdx < NumContextualBoolArguments) { 2424 assert(ParamTys[ArgIdx] == Context.BoolTy && 2425 "Contextual conversion to bool requires bool type"); 2426 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]); 2427 } else { 2428 Candidate.Conversions[ArgIdx] 2429 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], 2430 ArgIdx == 0 && IsAssignmentOperator); 2431 } 2432 if (Candidate.Conversions[ArgIdx].ConversionKind 2433 == ImplicitConversionSequence::BadConversion) { 2434 Candidate.Viable = false; 2435 break; 2436 } 2437 } 2438} 2439 2440/// BuiltinCandidateTypeSet - A set of types that will be used for the 2441/// candidate operator functions for built-in operators (C++ 2442/// [over.built]). The types are separated into pointer types and 2443/// enumeration types. 2444class BuiltinCandidateTypeSet { 2445 /// TypeSet - A set of types. 2446 typedef llvm::SmallPtrSet<void*, 8> TypeSet; 2447 2448 /// PointerTypes - The set of pointer types that will be used in the 2449 /// built-in candidates. 2450 TypeSet PointerTypes; 2451 2452 /// EnumerationTypes - The set of enumeration types that will be 2453 /// used in the built-in candidates. 2454 TypeSet EnumerationTypes; 2455 2456 /// Context - The AST context in which we will build the type sets. 2457 ASTContext &Context; 2458 2459 bool AddWithMoreQualifiedTypeVariants(QualType Ty); 2460 2461public: 2462 /// iterator - Iterates through the types that are part of the set. 2463 class iterator { 2464 TypeSet::iterator Base; 2465 2466 public: 2467 typedef QualType value_type; 2468 typedef QualType reference; 2469 typedef QualType pointer; 2470 typedef std::ptrdiff_t difference_type; 2471 typedef std::input_iterator_tag iterator_category; 2472 2473 iterator(TypeSet::iterator B) : Base(B) { } 2474 2475 iterator& operator++() { 2476 ++Base; 2477 return *this; 2478 } 2479 2480 iterator operator++(int) { 2481 iterator tmp(*this); 2482 ++(*this); 2483 return tmp; 2484 } 2485 2486 reference operator*() const { 2487 return QualType::getFromOpaquePtr(*Base); 2488 } 2489 2490 pointer operator->() const { 2491 return **this; 2492 } 2493 2494 friend bool operator==(iterator LHS, iterator RHS) { 2495 return LHS.Base == RHS.Base; 2496 } 2497 2498 friend bool operator!=(iterator LHS, iterator RHS) { 2499 return LHS.Base != RHS.Base; 2500 } 2501 }; 2502 2503 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { } 2504 2505 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions, 2506 bool AllowExplicitConversions); 2507 2508 /// pointer_begin - First pointer type found; 2509 iterator pointer_begin() { return PointerTypes.begin(); } 2510 2511 /// pointer_end - Last pointer type found; 2512 iterator pointer_end() { return PointerTypes.end(); } 2513 2514 /// enumeration_begin - First enumeration type found; 2515 iterator enumeration_begin() { return EnumerationTypes.begin(); } 2516 2517 /// enumeration_end - Last enumeration type found; 2518 iterator enumeration_end() { return EnumerationTypes.end(); } 2519}; 2520 2521/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 2522/// the set of pointer types along with any more-qualified variants of 2523/// that type. For example, if @p Ty is "int const *", this routine 2524/// will add "int const *", "int const volatile *", "int const 2525/// restrict *", and "int const volatile restrict *" to the set of 2526/// pointer types. Returns true if the add of @p Ty itself succeeded, 2527/// false otherwise. 2528bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) { 2529 // Insert this type. 2530 if (!PointerTypes.insert(Ty.getAsOpaquePtr())) 2531 return false; 2532 2533 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2534 QualType PointeeTy = PointerTy->getPointeeType(); 2535 // FIXME: Optimize this so that we don't keep trying to add the same types. 2536 2537 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal 2538 // with all pointer conversions that don't cast away constness? 2539 if (!PointeeTy.isConstQualified()) 2540 AddWithMoreQualifiedTypeVariants 2541 (Context.getPointerType(PointeeTy.withConst())); 2542 if (!PointeeTy.isVolatileQualified()) 2543 AddWithMoreQualifiedTypeVariants 2544 (Context.getPointerType(PointeeTy.withVolatile())); 2545 if (!PointeeTy.isRestrictQualified()) 2546 AddWithMoreQualifiedTypeVariants 2547 (Context.getPointerType(PointeeTy.withRestrict())); 2548 } 2549 2550 return true; 2551} 2552 2553/// AddTypesConvertedFrom - Add each of the types to which the type @p 2554/// Ty can be implicit converted to the given set of @p Types. We're 2555/// primarily interested in pointer types and enumeration types. 2556/// AllowUserConversions is true if we should look at the conversion 2557/// functions of a class type, and AllowExplicitConversions if we 2558/// should also include the explicit conversion functions of a class 2559/// type. 2560void 2561BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 2562 bool AllowUserConversions, 2563 bool AllowExplicitConversions) { 2564 // Only deal with canonical types. 2565 Ty = Context.getCanonicalType(Ty); 2566 2567 // Look through reference types; they aren't part of the type of an 2568 // expression for the purposes of conversions. 2569 if (const ReferenceType *RefTy = Ty->getAsReferenceType()) 2570 Ty = RefTy->getPointeeType(); 2571 2572 // We don't care about qualifiers on the type. 2573 Ty = Ty.getUnqualifiedType(); 2574 2575 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2576 QualType PointeeTy = PointerTy->getPointeeType(); 2577 2578 // Insert our type, and its more-qualified variants, into the set 2579 // of types. 2580 if (!AddWithMoreQualifiedTypeVariants(Ty)) 2581 return; 2582 2583 // Add 'cv void*' to our set of types. 2584 if (!Ty->isVoidType()) { 2585 QualType QualVoid 2586 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2587 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid)); 2588 } 2589 2590 // If this is a pointer to a class type, add pointers to its bases 2591 // (with the same level of cv-qualification as the original 2592 // derived class, of course). 2593 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) { 2594 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl()); 2595 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2596 Base != ClassDecl->bases_end(); ++Base) { 2597 QualType BaseTy = Context.getCanonicalType(Base->getType()); 2598 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2599 2600 // Add the pointer type, recursively, so that we get all of 2601 // the indirect base classes, too. 2602 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false); 2603 } 2604 } 2605 } else if (Ty->isEnumeralType()) { 2606 EnumerationTypes.insert(Ty.getAsOpaquePtr()); 2607 } else if (AllowUserConversions) { 2608 if (const RecordType *TyRec = Ty->getAsRecordType()) { 2609 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 2610 // FIXME: Visit conversion functions in the base classes, too. 2611 OverloadedFunctionDecl *Conversions 2612 = ClassDecl->getConversionFunctions(); 2613 for (OverloadedFunctionDecl::function_iterator Func 2614 = Conversions->function_begin(); 2615 Func != Conversions->function_end(); ++Func) { 2616 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 2617 if (AllowExplicitConversions || !Conv->isExplicit()) 2618 AddTypesConvertedFrom(Conv->getConversionType(), false, false); 2619 } 2620 } 2621 } 2622} 2623 2624/// AddBuiltinOperatorCandidates - Add the appropriate built-in 2625/// operator overloads to the candidate set (C++ [over.built]), based 2626/// on the operator @p Op and the arguments given. For example, if the 2627/// operator is a binary '+', this routine might add "int 2628/// operator+(int, int)" to cover integer addition. 2629void 2630Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2631 Expr **Args, unsigned NumArgs, 2632 OverloadCandidateSet& CandidateSet) { 2633 // The set of "promoted arithmetic types", which are the arithmetic 2634 // types are that preserved by promotion (C++ [over.built]p2). Note 2635 // that the first few of these types are the promoted integral 2636 // types; these types need to be first. 2637 // FIXME: What about complex? 2638 const unsigned FirstIntegralType = 0; 2639 const unsigned LastIntegralType = 13; 2640 const unsigned FirstPromotedIntegralType = 7, 2641 LastPromotedIntegralType = 13; 2642 const unsigned FirstPromotedArithmeticType = 7, 2643 LastPromotedArithmeticType = 16; 2644 const unsigned NumArithmeticTypes = 16; 2645 QualType ArithmeticTypes[NumArithmeticTypes] = { 2646 Context.BoolTy, Context.CharTy, Context.WCharTy, 2647 Context.SignedCharTy, Context.ShortTy, 2648 Context.UnsignedCharTy, Context.UnsignedShortTy, 2649 Context.IntTy, Context.LongTy, Context.LongLongTy, 2650 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 2651 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 2652 }; 2653 2654 // Find all of the types that the arguments can convert to, but only 2655 // if the operator we're looking at has built-in operator candidates 2656 // that make use of these types. 2657 BuiltinCandidateTypeSet CandidateTypes(Context); 2658 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 2659 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 2660 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 2661 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 2662 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 2663 (Op == OO_Star && NumArgs == 1)) { 2664 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2665 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(), 2666 true, 2667 (Op == OO_Exclaim || 2668 Op == OO_AmpAmp || 2669 Op == OO_PipePipe)); 2670 } 2671 2672 bool isComparison = false; 2673 switch (Op) { 2674 case OO_None: 2675 case NUM_OVERLOADED_OPERATORS: 2676 assert(false && "Expected an overloaded operator"); 2677 break; 2678 2679 case OO_Star: // '*' is either unary or binary 2680 if (NumArgs == 1) 2681 goto UnaryStar; 2682 else 2683 goto BinaryStar; 2684 break; 2685 2686 case OO_Plus: // '+' is either unary or binary 2687 if (NumArgs == 1) 2688 goto UnaryPlus; 2689 else 2690 goto BinaryPlus; 2691 break; 2692 2693 case OO_Minus: // '-' is either unary or binary 2694 if (NumArgs == 1) 2695 goto UnaryMinus; 2696 else 2697 goto BinaryMinus; 2698 break; 2699 2700 case OO_Amp: // '&' is either unary or binary 2701 if (NumArgs == 1) 2702 goto UnaryAmp; 2703 else 2704 goto BinaryAmp; 2705 2706 case OO_PlusPlus: 2707 case OO_MinusMinus: 2708 // C++ [over.built]p3: 2709 // 2710 // For every pair (T, VQ), where T is an arithmetic type, and VQ 2711 // is either volatile or empty, there exist candidate operator 2712 // functions of the form 2713 // 2714 // VQ T& operator++(VQ T&); 2715 // T operator++(VQ T&, int); 2716 // 2717 // C++ [over.built]p4: 2718 // 2719 // For every pair (T, VQ), where T is an arithmetic type other 2720 // than bool, and VQ is either volatile or empty, there exist 2721 // candidate operator functions of the form 2722 // 2723 // VQ T& operator--(VQ T&); 2724 // T operator--(VQ T&, int); 2725 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 2726 Arith < NumArithmeticTypes; ++Arith) { 2727 QualType ArithTy = ArithmeticTypes[Arith]; 2728 QualType ParamTypes[2] 2729 = { Context.getReferenceType(ArithTy), Context.IntTy }; 2730 2731 // Non-volatile version. 2732 if (NumArgs == 1) 2733 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2734 else 2735 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2736 2737 // Volatile version 2738 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile()); 2739 if (NumArgs == 1) 2740 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2741 else 2742 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2743 } 2744 2745 // C++ [over.built]p5: 2746 // 2747 // For every pair (T, VQ), where T is a cv-qualified or 2748 // cv-unqualified object type, and VQ is either volatile or 2749 // empty, there exist candidate operator functions of the form 2750 // 2751 // T*VQ& operator++(T*VQ&); 2752 // T*VQ& operator--(T*VQ&); 2753 // T* operator++(T*VQ&, int); 2754 // T* operator--(T*VQ&, int); 2755 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2756 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2757 // Skip pointer types that aren't pointers to object types. 2758 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType()) 2759 continue; 2760 2761 QualType ParamTypes[2] = { 2762 Context.getReferenceType(*Ptr), Context.IntTy 2763 }; 2764 2765 // Without volatile 2766 if (NumArgs == 1) 2767 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2768 else 2769 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2770 2771 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2772 // With volatile 2773 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2774 if (NumArgs == 1) 2775 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2776 else 2777 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2778 } 2779 } 2780 break; 2781 2782 UnaryStar: 2783 // C++ [over.built]p6: 2784 // For every cv-qualified or cv-unqualified object type T, there 2785 // exist candidate operator functions of the form 2786 // 2787 // T& operator*(T*); 2788 // 2789 // C++ [over.built]p7: 2790 // For every function type T, there exist candidate operator 2791 // functions of the form 2792 // T& operator*(T*); 2793 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2794 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2795 QualType ParamTy = *Ptr; 2796 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType(); 2797 AddBuiltinCandidate(Context.getReferenceType(PointeeTy), 2798 &ParamTy, Args, 1, CandidateSet); 2799 } 2800 break; 2801 2802 UnaryPlus: 2803 // C++ [over.built]p8: 2804 // For every type T, there exist candidate operator functions of 2805 // the form 2806 // 2807 // T* operator+(T*); 2808 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2809 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2810 QualType ParamTy = *Ptr; 2811 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2812 } 2813 2814 // Fall through 2815 2816 UnaryMinus: 2817 // C++ [over.built]p9: 2818 // For every promoted arithmetic type T, there exist candidate 2819 // operator functions of the form 2820 // 2821 // T operator+(T); 2822 // T operator-(T); 2823 for (unsigned Arith = FirstPromotedArithmeticType; 2824 Arith < LastPromotedArithmeticType; ++Arith) { 2825 QualType ArithTy = ArithmeticTypes[Arith]; 2826 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 2827 } 2828 break; 2829 2830 case OO_Tilde: 2831 // C++ [over.built]p10: 2832 // For every promoted integral type T, there exist candidate 2833 // operator functions of the form 2834 // 2835 // T operator~(T); 2836 for (unsigned Int = FirstPromotedIntegralType; 2837 Int < LastPromotedIntegralType; ++Int) { 2838 QualType IntTy = ArithmeticTypes[Int]; 2839 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 2840 } 2841 break; 2842 2843 case OO_New: 2844 case OO_Delete: 2845 case OO_Array_New: 2846 case OO_Array_Delete: 2847 case OO_Call: 2848 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 2849 break; 2850 2851 case OO_Comma: 2852 UnaryAmp: 2853 case OO_Arrow: 2854 // C++ [over.match.oper]p3: 2855 // -- For the operator ',', the unary operator '&', or the 2856 // operator '->', the built-in candidates set is empty. 2857 break; 2858 2859 case OO_Less: 2860 case OO_Greater: 2861 case OO_LessEqual: 2862 case OO_GreaterEqual: 2863 case OO_EqualEqual: 2864 case OO_ExclaimEqual: 2865 // C++ [over.built]p15: 2866 // 2867 // For every pointer or enumeration type T, there exist 2868 // candidate operator functions of the form 2869 // 2870 // bool operator<(T, T); 2871 // bool operator>(T, T); 2872 // bool operator<=(T, T); 2873 // bool operator>=(T, T); 2874 // bool operator==(T, T); 2875 // bool operator!=(T, T); 2876 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2877 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2878 QualType ParamTypes[2] = { *Ptr, *Ptr }; 2879 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2880 } 2881 for (BuiltinCandidateTypeSet::iterator Enum 2882 = CandidateTypes.enumeration_begin(); 2883 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2884 QualType ParamTypes[2] = { *Enum, *Enum }; 2885 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2886 } 2887 2888 // Fall through. 2889 isComparison = true; 2890 2891 BinaryPlus: 2892 BinaryMinus: 2893 if (!isComparison) { 2894 // We didn't fall through, so we must have OO_Plus or OO_Minus. 2895 2896 // C++ [over.built]p13: 2897 // 2898 // For every cv-qualified or cv-unqualified object type T 2899 // there exist candidate operator functions of the form 2900 // 2901 // T* operator+(T*, ptrdiff_t); 2902 // T& operator[](T*, ptrdiff_t); [BELOW] 2903 // T* operator-(T*, ptrdiff_t); 2904 // T* operator+(ptrdiff_t, T*); 2905 // T& operator[](ptrdiff_t, T*); [BELOW] 2906 // 2907 // C++ [over.built]p14: 2908 // 2909 // For every T, where T is a pointer to object type, there 2910 // exist candidate operator functions of the form 2911 // 2912 // ptrdiff_t operator-(T, T); 2913 for (BuiltinCandidateTypeSet::iterator Ptr 2914 = CandidateTypes.pointer_begin(); 2915 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2916 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2917 2918 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 2919 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2920 2921 if (Op == OO_Plus) { 2922 // T* operator+(ptrdiff_t, T*); 2923 ParamTypes[0] = ParamTypes[1]; 2924 ParamTypes[1] = *Ptr; 2925 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2926 } else { 2927 // ptrdiff_t operator-(T, T); 2928 ParamTypes[1] = *Ptr; 2929 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 2930 Args, 2, CandidateSet); 2931 } 2932 } 2933 } 2934 // Fall through 2935 2936 case OO_Slash: 2937 BinaryStar: 2938 // C++ [over.built]p12: 2939 // 2940 // For every pair of promoted arithmetic types L and R, there 2941 // exist candidate operator functions of the form 2942 // 2943 // LR operator*(L, R); 2944 // LR operator/(L, R); 2945 // LR operator+(L, R); 2946 // LR operator-(L, R); 2947 // bool operator<(L, R); 2948 // bool operator>(L, R); 2949 // bool operator<=(L, R); 2950 // bool operator>=(L, R); 2951 // bool operator==(L, R); 2952 // bool operator!=(L, R); 2953 // 2954 // where LR is the result of the usual arithmetic conversions 2955 // between types L and R. 2956 for (unsigned Left = FirstPromotedArithmeticType; 2957 Left < LastPromotedArithmeticType; ++Left) { 2958 for (unsigned Right = FirstPromotedArithmeticType; 2959 Right < LastPromotedArithmeticType; ++Right) { 2960 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2961 QualType Result 2962 = isComparison? Context.BoolTy 2963 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2964 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2965 } 2966 } 2967 break; 2968 2969 case OO_Percent: 2970 BinaryAmp: 2971 case OO_Caret: 2972 case OO_Pipe: 2973 case OO_LessLess: 2974 case OO_GreaterGreater: 2975 // C++ [over.built]p17: 2976 // 2977 // For every pair of promoted integral types L and R, there 2978 // exist candidate operator functions of the form 2979 // 2980 // LR operator%(L, R); 2981 // LR operator&(L, R); 2982 // LR operator^(L, R); 2983 // LR operator|(L, R); 2984 // L operator<<(L, R); 2985 // L operator>>(L, R); 2986 // 2987 // where LR is the result of the usual arithmetic conversions 2988 // between types L and R. 2989 for (unsigned Left = FirstPromotedIntegralType; 2990 Left < LastPromotedIntegralType; ++Left) { 2991 for (unsigned Right = FirstPromotedIntegralType; 2992 Right < LastPromotedIntegralType; ++Right) { 2993 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2994 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 2995 ? LandR[0] 2996 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2997 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2998 } 2999 } 3000 break; 3001 3002 case OO_Equal: 3003 // C++ [over.built]p20: 3004 // 3005 // For every pair (T, VQ), where T is an enumeration or 3006 // (FIXME:) pointer to member type and VQ is either volatile or 3007 // empty, there exist candidate operator functions of the form 3008 // 3009 // VQ T& operator=(VQ T&, T); 3010 for (BuiltinCandidateTypeSet::iterator Enum 3011 = CandidateTypes.enumeration_begin(); 3012 Enum != CandidateTypes.enumeration_end(); ++Enum) { 3013 QualType ParamTypes[2]; 3014 3015 // T& operator=(T&, T) 3016 ParamTypes[0] = Context.getReferenceType(*Enum); 3017 ParamTypes[1] = *Enum; 3018 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3019 /*IsAssignmentOperator=*/false); 3020 3021 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) { 3022 // volatile T& operator=(volatile T&, T) 3023 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile()); 3024 ParamTypes[1] = *Enum; 3025 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3026 /*IsAssignmentOperator=*/false); 3027 } 3028 } 3029 // Fall through. 3030 3031 case OO_PlusEqual: 3032 case OO_MinusEqual: 3033 // C++ [over.built]p19: 3034 // 3035 // For every pair (T, VQ), where T is any type and VQ is either 3036 // volatile or empty, there exist candidate operator functions 3037 // of the form 3038 // 3039 // T*VQ& operator=(T*VQ&, T*); 3040 // 3041 // C++ [over.built]p21: 3042 // 3043 // For every pair (T, VQ), where T is a cv-qualified or 3044 // cv-unqualified object type and VQ is either volatile or 3045 // empty, there exist candidate operator functions of the form 3046 // 3047 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 3048 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 3049 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3050 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3051 QualType ParamTypes[2]; 3052 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 3053 3054 // non-volatile version 3055 ParamTypes[0] = Context.getReferenceType(*Ptr); 3056 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3057 /*IsAssigmentOperator=*/Op == OO_Equal); 3058 3059 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 3060 // volatile version 3061 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 3062 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3063 /*IsAssigmentOperator=*/Op == OO_Equal); 3064 } 3065 } 3066 // Fall through. 3067 3068 case OO_StarEqual: 3069 case OO_SlashEqual: 3070 // C++ [over.built]p18: 3071 // 3072 // For every triple (L, VQ, R), where L is an arithmetic type, 3073 // VQ is either volatile or empty, and R is a promoted 3074 // arithmetic type, there exist candidate operator functions of 3075 // the form 3076 // 3077 // VQ L& operator=(VQ L&, R); 3078 // VQ L& operator*=(VQ L&, R); 3079 // VQ L& operator/=(VQ L&, R); 3080 // VQ L& operator+=(VQ L&, R); 3081 // VQ L& operator-=(VQ L&, R); 3082 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 3083 for (unsigned Right = FirstPromotedArithmeticType; 3084 Right < LastPromotedArithmeticType; ++Right) { 3085 QualType ParamTypes[2]; 3086 ParamTypes[1] = ArithmeticTypes[Right]; 3087 3088 // Add this built-in operator as a candidate (VQ is empty). 3089 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 3090 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3091 /*IsAssigmentOperator=*/Op == OO_Equal); 3092 3093 // Add this built-in operator as a candidate (VQ is 'volatile'). 3094 ParamTypes[0] = ArithmeticTypes[Left].withVolatile(); 3095 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 3096 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3097 /*IsAssigmentOperator=*/Op == OO_Equal); 3098 } 3099 } 3100 break; 3101 3102 case OO_PercentEqual: 3103 case OO_LessLessEqual: 3104 case OO_GreaterGreaterEqual: 3105 case OO_AmpEqual: 3106 case OO_CaretEqual: 3107 case OO_PipeEqual: 3108 // C++ [over.built]p22: 3109 // 3110 // For every triple (L, VQ, R), where L is an integral type, VQ 3111 // is either volatile or empty, and R is a promoted integral 3112 // type, there exist candidate operator functions of the form 3113 // 3114 // VQ L& operator%=(VQ L&, R); 3115 // VQ L& operator<<=(VQ L&, R); 3116 // VQ L& operator>>=(VQ L&, R); 3117 // VQ L& operator&=(VQ L&, R); 3118 // VQ L& operator^=(VQ L&, R); 3119 // VQ L& operator|=(VQ L&, R); 3120 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 3121 for (unsigned Right = FirstPromotedIntegralType; 3122 Right < LastPromotedIntegralType; ++Right) { 3123 QualType ParamTypes[2]; 3124 ParamTypes[1] = ArithmeticTypes[Right]; 3125 3126 // Add this built-in operator as a candidate (VQ is empty). 3127 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 3128 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 3129 3130 // Add this built-in operator as a candidate (VQ is 'volatile'). 3131 ParamTypes[0] = ArithmeticTypes[Left]; 3132 ParamTypes[0].addVolatile(); 3133 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 3134 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 3135 } 3136 } 3137 break; 3138 3139 case OO_Exclaim: { 3140 // C++ [over.operator]p23: 3141 // 3142 // There also exist candidate operator functions of the form 3143 // 3144 // bool operator!(bool); 3145 // bool operator&&(bool, bool); [BELOW] 3146 // bool operator||(bool, bool); [BELOW] 3147 QualType ParamTy = Context.BoolTy; 3148 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 3149 /*IsAssignmentOperator=*/false, 3150 /*NumContextualBoolArguments=*/1); 3151 break; 3152 } 3153 3154 case OO_AmpAmp: 3155 case OO_PipePipe: { 3156 // C++ [over.operator]p23: 3157 // 3158 // There also exist candidate operator functions of the form 3159 // 3160 // bool operator!(bool); [ABOVE] 3161 // bool operator&&(bool, bool); 3162 // bool operator||(bool, bool); 3163 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 3164 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 3165 /*IsAssignmentOperator=*/false, 3166 /*NumContextualBoolArguments=*/2); 3167 break; 3168 } 3169 3170 case OO_Subscript: 3171 // C++ [over.built]p13: 3172 // 3173 // For every cv-qualified or cv-unqualified object type T there 3174 // exist candidate operator functions of the form 3175 // 3176 // T* operator+(T*, ptrdiff_t); [ABOVE] 3177 // T& operator[](T*, ptrdiff_t); 3178 // T* operator-(T*, ptrdiff_t); [ABOVE] 3179 // T* operator+(ptrdiff_t, T*); [ABOVE] 3180 // T& operator[](ptrdiff_t, T*); 3181 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3182 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3183 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 3184 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType(); 3185 QualType ResultTy = Context.getReferenceType(PointeeType); 3186 3187 // T& operator[](T*, ptrdiff_t) 3188 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 3189 3190 // T& operator[](ptrdiff_t, T*); 3191 ParamTypes[0] = ParamTypes[1]; 3192 ParamTypes[1] = *Ptr; 3193 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 3194 } 3195 break; 3196 3197 case OO_ArrowStar: 3198 // FIXME: No support for pointer-to-members yet. 3199 break; 3200 } 3201} 3202 3203/// \brief Add function candidates found via argument-dependent lookup 3204/// to the set of overloading candidates. 3205/// 3206/// This routine performs argument-dependent name lookup based on the 3207/// given function name (which may also be an operator name) and adds 3208/// all of the overload candidates found by ADL to the overload 3209/// candidate set (C++ [basic.lookup.argdep]). 3210void 3211Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 3212 Expr **Args, unsigned NumArgs, 3213 OverloadCandidateSet& CandidateSet) { 3214 FunctionSet Functions; 3215 3216 // Record all of the function candidates that we've already 3217 // added to the overload set, so that we don't add those same 3218 // candidates a second time. 3219 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3220 CandEnd = CandidateSet.end(); 3221 Cand != CandEnd; ++Cand) 3222 if (Cand->Function) 3223 Functions.insert(Cand->Function); 3224 3225 ArgumentDependentLookup(Name, Args, NumArgs, Functions); 3226 3227 // Erase all of the candidates we already knew about. 3228 // FIXME: This is suboptimal. Is there a better way? 3229 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3230 CandEnd = CandidateSet.end(); 3231 Cand != CandEnd; ++Cand) 3232 if (Cand->Function) 3233 Functions.erase(Cand->Function); 3234 3235 // For each of the ADL candidates we found, add it to the overload 3236 // set. 3237 for (FunctionSet::iterator Func = Functions.begin(), 3238 FuncEnd = Functions.end(); 3239 Func != FuncEnd; ++Func) 3240 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet); 3241} 3242 3243/// isBetterOverloadCandidate - Determines whether the first overload 3244/// candidate is a better candidate than the second (C++ 13.3.3p1). 3245bool 3246Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 3247 const OverloadCandidate& Cand2) 3248{ 3249 // Define viable functions to be better candidates than non-viable 3250 // functions. 3251 if (!Cand2.Viable) 3252 return Cand1.Viable; 3253 else if (!Cand1.Viable) 3254 return false; 3255 3256 // C++ [over.match.best]p1: 3257 // 3258 // -- if F is a static member function, ICS1(F) is defined such 3259 // that ICS1(F) is neither better nor worse than ICS1(G) for 3260 // any function G, and, symmetrically, ICS1(G) is neither 3261 // better nor worse than ICS1(F). 3262 unsigned StartArg = 0; 3263 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 3264 StartArg = 1; 3265 3266 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 3267 // function than another viable function F2 if for all arguments i, 3268 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 3269 // then... 3270 unsigned NumArgs = Cand1.Conversions.size(); 3271 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 3272 bool HasBetterConversion = false; 3273 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 3274 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 3275 Cand2.Conversions[ArgIdx])) { 3276 case ImplicitConversionSequence::Better: 3277 // Cand1 has a better conversion sequence. 3278 HasBetterConversion = true; 3279 break; 3280 3281 case ImplicitConversionSequence::Worse: 3282 // Cand1 can't be better than Cand2. 3283 return false; 3284 3285 case ImplicitConversionSequence::Indistinguishable: 3286 // Do nothing. 3287 break; 3288 } 3289 } 3290 3291 if (HasBetterConversion) 3292 return true; 3293 3294 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be 3295 // implemented, but they require template support. 3296 3297 // C++ [over.match.best]p1b4: 3298 // 3299 // -- the context is an initialization by user-defined conversion 3300 // (see 8.5, 13.3.1.5) and the standard conversion sequence 3301 // from the return type of F1 to the destination type (i.e., 3302 // the type of the entity being initialized) is a better 3303 // conversion sequence than the standard conversion sequence 3304 // from the return type of F2 to the destination type. 3305 if (Cand1.Function && Cand2.Function && 3306 isa<CXXConversionDecl>(Cand1.Function) && 3307 isa<CXXConversionDecl>(Cand2.Function)) { 3308 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 3309 Cand2.FinalConversion)) { 3310 case ImplicitConversionSequence::Better: 3311 // Cand1 has a better conversion sequence. 3312 return true; 3313 3314 case ImplicitConversionSequence::Worse: 3315 // Cand1 can't be better than Cand2. 3316 return false; 3317 3318 case ImplicitConversionSequence::Indistinguishable: 3319 // Do nothing 3320 break; 3321 } 3322 } 3323 3324 return false; 3325} 3326 3327/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 3328/// within an overload candidate set. If overloading is successful, 3329/// the result will be OR_Success and Best will be set to point to the 3330/// best viable function within the candidate set. Otherwise, one of 3331/// several kinds of errors will be returned; see 3332/// Sema::OverloadingResult. 3333Sema::OverloadingResult 3334Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 3335 OverloadCandidateSet::iterator& Best) 3336{ 3337 // Find the best viable function. 3338 Best = CandidateSet.end(); 3339 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3340 Cand != CandidateSet.end(); ++Cand) { 3341 if (Cand->Viable) { 3342 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 3343 Best = Cand; 3344 } 3345 } 3346 3347 // If we didn't find any viable functions, abort. 3348 if (Best == CandidateSet.end()) 3349 return OR_No_Viable_Function; 3350 3351 // Make sure that this function is better than every other viable 3352 // function. If not, we have an ambiguity. 3353 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3354 Cand != CandidateSet.end(); ++Cand) { 3355 if (Cand->Viable && 3356 Cand != Best && 3357 !isBetterOverloadCandidate(*Best, *Cand)) { 3358 Best = CandidateSet.end(); 3359 return OR_Ambiguous; 3360 } 3361 } 3362 3363 // Best is the best viable function. 3364 if (Best->Function && 3365 (Best->Function->isDeleted() || 3366 Best->Function->getAttr<UnavailableAttr>())) 3367 return OR_Deleted; 3368 3369 // If Best refers to a function that is either deleted (C++0x) or 3370 // unavailable (Clang extension) report an error. 3371 3372 return OR_Success; 3373} 3374 3375/// PrintOverloadCandidates - When overload resolution fails, prints 3376/// diagnostic messages containing the candidates in the candidate 3377/// set. If OnlyViable is true, only viable candidates will be printed. 3378void 3379Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 3380 bool OnlyViable) 3381{ 3382 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3383 LastCand = CandidateSet.end(); 3384 for (; Cand != LastCand; ++Cand) { 3385 if (Cand->Viable || !OnlyViable) { 3386 if (Cand->Function) { 3387 if (Cand->Function->isDeleted() || 3388 Cand->Function->getAttr<UnavailableAttr>()) { 3389 // Deleted or "unavailable" function. 3390 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted) 3391 << Cand->Function->isDeleted(); 3392 } else { 3393 // Normal function 3394 // FIXME: Give a better reason! 3395 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 3396 } 3397 } else if (Cand->IsSurrogate) { 3398 // Desugar the type of the surrogate down to a function type, 3399 // retaining as many typedefs as possible while still showing 3400 // the function type (and, therefore, its parameter types). 3401 QualType FnType = Cand->Surrogate->getConversionType(); 3402 bool isReference = false; 3403 bool isPointer = false; 3404 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) { 3405 FnType = FnTypeRef->getPointeeType(); 3406 isReference = true; 3407 } 3408 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) { 3409 FnType = FnTypePtr->getPointeeType(); 3410 isPointer = true; 3411 } 3412 // Desugar down to a function type. 3413 FnType = QualType(FnType->getAsFunctionType(), 0); 3414 // Reconstruct the pointer/reference as appropriate. 3415 if (isPointer) FnType = Context.getPointerType(FnType); 3416 if (isReference) FnType = Context.getReferenceType(FnType); 3417 3418 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand) 3419 << FnType; 3420 } else { 3421 // FIXME: We need to get the identifier in here 3422 // FIXME: Do we want the error message to point at the 3423 // operator? (built-ins won't have a location) 3424 QualType FnType 3425 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy, 3426 Cand->BuiltinTypes.ParamTypes, 3427 Cand->Conversions.size(), 3428 false, 0); 3429 3430 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType; 3431 } 3432 } 3433 } 3434} 3435 3436/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 3437/// an overloaded function (C++ [over.over]), where @p From is an 3438/// expression with overloaded function type and @p ToType is the type 3439/// we're trying to resolve to. For example: 3440/// 3441/// @code 3442/// int f(double); 3443/// int f(int); 3444/// 3445/// int (*pfd)(double) = f; // selects f(double) 3446/// @endcode 3447/// 3448/// This routine returns the resulting FunctionDecl if it could be 3449/// resolved, and NULL otherwise. When @p Complain is true, this 3450/// routine will emit diagnostics if there is an error. 3451FunctionDecl * 3452Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 3453 bool Complain) { 3454 QualType FunctionType = ToType; 3455 bool IsMember = false; 3456 if (const PointerType *ToTypePtr = ToType->getAsPointerType()) 3457 FunctionType = ToTypePtr->getPointeeType(); 3458 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType()) 3459 FunctionType = ToTypeRef->getPointeeType(); 3460 else if (const MemberPointerType *MemTypePtr = 3461 ToType->getAsMemberPointerType()) { 3462 FunctionType = MemTypePtr->getPointeeType(); 3463 IsMember = true; 3464 } 3465 3466 // We only look at pointers or references to functions. 3467 if (!FunctionType->isFunctionType()) 3468 return 0; 3469 3470 // Find the actual overloaded function declaration. 3471 OverloadedFunctionDecl *Ovl = 0; 3472 3473 // C++ [over.over]p1: 3474 // [...] [Note: any redundant set of parentheses surrounding the 3475 // overloaded function name is ignored (5.1). ] 3476 Expr *OvlExpr = From->IgnoreParens(); 3477 3478 // C++ [over.over]p1: 3479 // [...] The overloaded function name can be preceded by the & 3480 // operator. 3481 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) { 3482 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 3483 OvlExpr = UnOp->getSubExpr()->IgnoreParens(); 3484 } 3485 3486 // Try to dig out the overloaded function. 3487 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) 3488 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl()); 3489 3490 // If there's no overloaded function declaration, we're done. 3491 if (!Ovl) 3492 return 0; 3493 3494 // Look through all of the overloaded functions, searching for one 3495 // whose type matches exactly. 3496 // FIXME: When templates or using declarations come along, we'll actually 3497 // have to deal with duplicates, partial ordering, etc. For now, we 3498 // can just do a simple search. 3499 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType()); 3500 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin(); 3501 Fun != Ovl->function_end(); ++Fun) { 3502 // C++ [over.over]p3: 3503 // Non-member functions and static member functions match 3504 // targets of type "pointer-to-function" or "reference-to-function." 3505 // Nonstatic member functions match targets of 3506 // type "pointer-to-member-function." 3507 // Note that according to DR 247, the containing class does not matter. 3508 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) { 3509 // Skip non-static functions when converting to pointer, and static 3510 // when converting to member pointer. 3511 if (Method->isStatic() == IsMember) 3512 continue; 3513 } else if (IsMember) 3514 continue; 3515 3516 if (FunctionType == Context.getCanonicalType((*Fun)->getType())) 3517 return *Fun; 3518 } 3519 3520 return 0; 3521} 3522 3523/// ResolveOverloadedCallFn - Given the call expression that calls Fn 3524/// (which eventually refers to the declaration Func) and the call 3525/// arguments Args/NumArgs, attempt to resolve the function call down 3526/// to a specific function. If overload resolution succeeds, returns 3527/// the function declaration produced by overload 3528/// resolution. Otherwise, emits diagnostics, deletes all of the 3529/// arguments and Fn, and returns NULL. 3530FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee, 3531 DeclarationName UnqualifiedName, 3532 SourceLocation LParenLoc, 3533 Expr **Args, unsigned NumArgs, 3534 SourceLocation *CommaLocs, 3535 SourceLocation RParenLoc, 3536 bool &ArgumentDependentLookup) { 3537 OverloadCandidateSet CandidateSet; 3538 3539 // Add the functions denoted by Callee to the set of candidate 3540 // functions. While we're doing so, track whether argument-dependent 3541 // lookup still applies, per: 3542 // 3543 // C++0x [basic.lookup.argdep]p3: 3544 // Let X be the lookup set produced by unqualified lookup (3.4.1) 3545 // and let Y be the lookup set produced by argument dependent 3546 // lookup (defined as follows). If X contains 3547 // 3548 // -- a declaration of a class member, or 3549 // 3550 // -- a block-scope function declaration that is not a 3551 // using-declaration, or 3552 // 3553 // -- a declaration that is neither a function or a function 3554 // template 3555 // 3556 // then Y is empty. 3557 if (OverloadedFunctionDecl *Ovl 3558 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) { 3559 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 3560 FuncEnd = Ovl->function_end(); 3561 Func != FuncEnd; ++Func) { 3562 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet); 3563 3564 if ((*Func)->getDeclContext()->isRecord() || 3565 (*Func)->getDeclContext()->isFunctionOrMethod()) 3566 ArgumentDependentLookup = false; 3567 } 3568 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) { 3569 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet); 3570 3571 if (Func->getDeclContext()->isRecord() || 3572 Func->getDeclContext()->isFunctionOrMethod()) 3573 ArgumentDependentLookup = false; 3574 } 3575 3576 if (Callee) 3577 UnqualifiedName = Callee->getDeclName(); 3578 3579 if (ArgumentDependentLookup) 3580 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs, 3581 CandidateSet); 3582 3583 OverloadCandidateSet::iterator Best; 3584 switch (BestViableFunction(CandidateSet, Best)) { 3585 case OR_Success: 3586 return Best->Function; 3587 3588 case OR_No_Viable_Function: 3589 Diag(Fn->getSourceRange().getBegin(), 3590 diag::err_ovl_no_viable_function_in_call) 3591 << UnqualifiedName << Fn->getSourceRange(); 3592 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3593 break; 3594 3595 case OR_Ambiguous: 3596 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 3597 << UnqualifiedName << Fn->getSourceRange(); 3598 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3599 break; 3600 3601 case OR_Deleted: 3602 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 3603 << Best->Function->isDeleted() 3604 << UnqualifiedName 3605 << Fn->getSourceRange(); 3606 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3607 break; 3608 } 3609 3610 // Overload resolution failed. Destroy all of the subexpressions and 3611 // return NULL. 3612 Fn->Destroy(Context); 3613 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 3614 Args[Arg]->Destroy(Context); 3615 return 0; 3616} 3617 3618/// BuildCallToMemberFunction - Build a call to a member 3619/// function. MemExpr is the expression that refers to the member 3620/// function (and includes the object parameter), Args/NumArgs are the 3621/// arguments to the function call (not including the object 3622/// parameter). The caller needs to validate that the member 3623/// expression refers to a member function or an overloaded member 3624/// function. 3625Sema::ExprResult 3626Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 3627 SourceLocation LParenLoc, Expr **Args, 3628 unsigned NumArgs, SourceLocation *CommaLocs, 3629 SourceLocation RParenLoc) { 3630 // Dig out the member expression. This holds both the object 3631 // argument and the member function we're referring to. 3632 MemberExpr *MemExpr = 0; 3633 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE)) 3634 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr()); 3635 else 3636 MemExpr = dyn_cast<MemberExpr>(MemExprE); 3637 assert(MemExpr && "Building member call without member expression"); 3638 3639 // Extract the object argument. 3640 Expr *ObjectArg = MemExpr->getBase(); 3641 if (MemExpr->isArrow()) 3642 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref, 3643 ObjectArg->getType()->getAsPointerType()->getPointeeType(), 3644 ObjectArg->getLocStart()); 3645 CXXMethodDecl *Method = 0; 3646 if (OverloadedFunctionDecl *Ovl 3647 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) { 3648 // Add overload candidates 3649 OverloadCandidateSet CandidateSet; 3650 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 3651 FuncEnd = Ovl->function_end(); 3652 Func != FuncEnd; ++Func) { 3653 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method"); 3654 Method = cast<CXXMethodDecl>(*Func); 3655 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet, 3656 /*SuppressUserConversions=*/false); 3657 } 3658 3659 OverloadCandidateSet::iterator Best; 3660 switch (BestViableFunction(CandidateSet, Best)) { 3661 case OR_Success: 3662 Method = cast<CXXMethodDecl>(Best->Function); 3663 break; 3664 3665 case OR_No_Viable_Function: 3666 Diag(MemExpr->getSourceRange().getBegin(), 3667 diag::err_ovl_no_viable_member_function_in_call) 3668 << Ovl->getDeclName() << MemExprE->getSourceRange(); 3669 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3670 // FIXME: Leaking incoming expressions! 3671 return true; 3672 3673 case OR_Ambiguous: 3674 Diag(MemExpr->getSourceRange().getBegin(), 3675 diag::err_ovl_ambiguous_member_call) 3676 << Ovl->getDeclName() << MemExprE->getSourceRange(); 3677 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3678 // FIXME: Leaking incoming expressions! 3679 return true; 3680 3681 case OR_Deleted: 3682 Diag(MemExpr->getSourceRange().getBegin(), 3683 diag::err_ovl_deleted_member_call) 3684 << Best->Function->isDeleted() 3685 << Ovl->getDeclName() << MemExprE->getSourceRange(); 3686 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3687 // FIXME: Leaking incoming expressions! 3688 return true; 3689 } 3690 3691 FixOverloadedFunctionReference(MemExpr, Method); 3692 } else { 3693 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 3694 } 3695 3696 assert(Method && "Member call to something that isn't a method?"); 3697 ExprOwningPtr<CXXMemberCallExpr> 3698 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args, 3699 NumArgs, 3700 Method->getResultType().getNonReferenceType(), 3701 RParenLoc)); 3702 3703 // Convert the object argument (for a non-static member function call). 3704 if (!Method->isStatic() && 3705 PerformObjectArgumentInitialization(ObjectArg, Method)) 3706 return true; 3707 MemExpr->setBase(ObjectArg); 3708 3709 // Convert the rest of the arguments 3710 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType()); 3711 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs, 3712 RParenLoc)) 3713 return true; 3714 3715 return CheckFunctionCall(Method, TheCall.take()).release(); 3716} 3717 3718/// BuildCallToObjectOfClassType - Build a call to an object of class 3719/// type (C++ [over.call.object]), which can end up invoking an 3720/// overloaded function call operator (@c operator()) or performing a 3721/// user-defined conversion on the object argument. 3722Sema::ExprResult 3723Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 3724 SourceLocation LParenLoc, 3725 Expr **Args, unsigned NumArgs, 3726 SourceLocation *CommaLocs, 3727 SourceLocation RParenLoc) { 3728 assert(Object->getType()->isRecordType() && "Requires object type argument"); 3729 const RecordType *Record = Object->getType()->getAsRecordType(); 3730 3731 // C++ [over.call.object]p1: 3732 // If the primary-expression E in the function call syntax 3733 // evaluates to a class object of type “cv T”, then the set of 3734 // candidate functions includes at least the function call 3735 // operators of T. The function call operators of T are obtained by 3736 // ordinary lookup of the name operator() in the context of 3737 // (E).operator(). 3738 OverloadCandidateSet CandidateSet; 3739 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 3740 DeclContext::lookup_const_iterator Oper, OperEnd; 3741 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName); 3742 Oper != OperEnd; ++Oper) 3743 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs, 3744 CandidateSet, /*SuppressUserConversions=*/false); 3745 3746 // C++ [over.call.object]p2: 3747 // In addition, for each conversion function declared in T of the 3748 // form 3749 // 3750 // operator conversion-type-id () cv-qualifier; 3751 // 3752 // where cv-qualifier is the same cv-qualification as, or a 3753 // greater cv-qualification than, cv, and where conversion-type-id 3754 // denotes the type "pointer to function of (P1,...,Pn) returning 3755 // R", or the type "reference to pointer to function of 3756 // (P1,...,Pn) returning R", or the type "reference to function 3757 // of (P1,...,Pn) returning R", a surrogate call function [...] 3758 // is also considered as a candidate function. Similarly, 3759 // surrogate call functions are added to the set of candidate 3760 // functions for each conversion function declared in an 3761 // accessible base class provided the function is not hidden 3762 // within T by another intervening declaration. 3763 // 3764 // FIXME: Look in base classes for more conversion operators! 3765 OverloadedFunctionDecl *Conversions 3766 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions(); 3767 for (OverloadedFunctionDecl::function_iterator 3768 Func = Conversions->function_begin(), 3769 FuncEnd = Conversions->function_end(); 3770 Func != FuncEnd; ++Func) { 3771 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 3772 3773 // Strip the reference type (if any) and then the pointer type (if 3774 // any) to get down to what might be a function type. 3775 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 3776 if (const PointerType *ConvPtrType = ConvType->getAsPointerType()) 3777 ConvType = ConvPtrType->getPointeeType(); 3778 3779 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType()) 3780 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet); 3781 } 3782 3783 // Perform overload resolution. 3784 OverloadCandidateSet::iterator Best; 3785 switch (BestViableFunction(CandidateSet, Best)) { 3786 case OR_Success: 3787 // Overload resolution succeeded; we'll build the appropriate call 3788 // below. 3789 break; 3790 3791 case OR_No_Viable_Function: 3792 Diag(Object->getSourceRange().getBegin(), 3793 diag::err_ovl_no_viable_object_call) 3794 << Object->getType() << Object->getSourceRange(); 3795 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3796 break; 3797 3798 case OR_Ambiguous: 3799 Diag(Object->getSourceRange().getBegin(), 3800 diag::err_ovl_ambiguous_object_call) 3801 << Object->getType() << Object->getSourceRange(); 3802 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3803 break; 3804 3805 case OR_Deleted: 3806 Diag(Object->getSourceRange().getBegin(), 3807 diag::err_ovl_deleted_object_call) 3808 << Best->Function->isDeleted() 3809 << Object->getType() << Object->getSourceRange(); 3810 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3811 break; 3812 } 3813 3814 if (Best == CandidateSet.end()) { 3815 // We had an error; delete all of the subexpressions and return 3816 // the error. 3817 Object->Destroy(Context); 3818 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3819 Args[ArgIdx]->Destroy(Context); 3820 return true; 3821 } 3822 3823 if (Best->Function == 0) { 3824 // Since there is no function declaration, this is one of the 3825 // surrogate candidates. Dig out the conversion function. 3826 CXXConversionDecl *Conv 3827 = cast<CXXConversionDecl>( 3828 Best->Conversions[0].UserDefined.ConversionFunction); 3829 3830 // We selected one of the surrogate functions that converts the 3831 // object parameter to a function pointer. Perform the conversion 3832 // on the object argument, then let ActOnCallExpr finish the job. 3833 // FIXME: Represent the user-defined conversion in the AST! 3834 ImpCastExprToType(Object, 3835 Conv->getConversionType().getNonReferenceType(), 3836 Conv->getConversionType()->isReferenceType()); 3837 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc, 3838 MultiExprArg(*this, (ExprTy**)Args, NumArgs), 3839 CommaLocs, RParenLoc).release(); 3840 } 3841 3842 // We found an overloaded operator(). Build a CXXOperatorCallExpr 3843 // that calls this method, using Object for the implicit object 3844 // parameter and passing along the remaining arguments. 3845 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3846 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType(); 3847 3848 unsigned NumArgsInProto = Proto->getNumArgs(); 3849 unsigned NumArgsToCheck = NumArgs; 3850 3851 // Build the full argument list for the method call (the 3852 // implicit object parameter is placed at the beginning of the 3853 // list). 3854 Expr **MethodArgs; 3855 if (NumArgs < NumArgsInProto) { 3856 NumArgsToCheck = NumArgsInProto; 3857 MethodArgs = new Expr*[NumArgsInProto + 1]; 3858 } else { 3859 MethodArgs = new Expr*[NumArgs + 1]; 3860 } 3861 MethodArgs[0] = Object; 3862 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3863 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 3864 3865 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 3866 SourceLocation()); 3867 UsualUnaryConversions(NewFn); 3868 3869 // Once we've built TheCall, all of the expressions are properly 3870 // owned. 3871 QualType ResultTy = Method->getResultType().getNonReferenceType(); 3872 ExprOwningPtr<CXXOperatorCallExpr> 3873 TheCall(this, new (Context) CXXOperatorCallExpr(Context, NewFn, MethodArgs, 3874 NumArgs + 1, 3875 ResultTy, RParenLoc)); 3876 delete [] MethodArgs; 3877 3878 // We may have default arguments. If so, we need to allocate more 3879 // slots in the call for them. 3880 if (NumArgs < NumArgsInProto) 3881 TheCall->setNumArgs(Context, NumArgsInProto + 1); 3882 else if (NumArgs > NumArgsInProto) 3883 NumArgsToCheck = NumArgsInProto; 3884 3885 // Initialize the implicit object parameter. 3886 if (PerformObjectArgumentInitialization(Object, Method)) 3887 return true; 3888 TheCall->setArg(0, Object); 3889 3890 // Check the argument types. 3891 for (unsigned i = 0; i != NumArgsToCheck; i++) { 3892 Expr *Arg; 3893 if (i < NumArgs) { 3894 Arg = Args[i]; 3895 3896 // Pass the argument. 3897 QualType ProtoArgType = Proto->getArgType(i); 3898 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 3899 return true; 3900 } else { 3901 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i)); 3902 } 3903 3904 TheCall->setArg(i + 1, Arg); 3905 } 3906 3907 // If this is a variadic call, handle args passed through "...". 3908 if (Proto->isVariadic()) { 3909 // Promote the arguments (C99 6.5.2.2p7). 3910 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 3911 Expr *Arg = Args[i]; 3912 3913 DefaultVariadicArgumentPromotion(Arg, VariadicMethod); 3914 TheCall->setArg(i + 1, Arg); 3915 } 3916 } 3917 3918 return CheckFunctionCall(Method, TheCall.take()).release(); 3919} 3920 3921/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 3922/// (if one exists), where @c Base is an expression of class type and 3923/// @c Member is the name of the member we're trying to find. 3924Action::ExprResult 3925Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 3926 SourceLocation MemberLoc, 3927 IdentifierInfo &Member) { 3928 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 3929 3930 // C++ [over.ref]p1: 3931 // 3932 // [...] An expression x->m is interpreted as (x.operator->())->m 3933 // for a class object x of type T if T::operator->() exists and if 3934 // the operator is selected as the best match function by the 3935 // overload resolution mechanism (13.3). 3936 // FIXME: look in base classes. 3937 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 3938 OverloadCandidateSet CandidateSet; 3939 const RecordType *BaseRecord = Base->getType()->getAsRecordType(); 3940 3941 DeclContext::lookup_const_iterator Oper, OperEnd; 3942 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName); 3943 Oper != OperEnd; ++Oper) 3944 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet, 3945 /*SuppressUserConversions=*/false); 3946 3947 ExprOwningPtr<Expr> BasePtr(this, Base); 3948 3949 // Perform overload resolution. 3950 OverloadCandidateSet::iterator Best; 3951 switch (BestViableFunction(CandidateSet, Best)) { 3952 case OR_Success: 3953 // Overload resolution succeeded; we'll build the call below. 3954 break; 3955 3956 case OR_No_Viable_Function: 3957 if (CandidateSet.empty()) 3958 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 3959 << BasePtr->getType() << BasePtr->getSourceRange(); 3960 else 3961 Diag(OpLoc, diag::err_ovl_no_viable_oper) 3962 << "operator->" << BasePtr->getSourceRange(); 3963 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3964 return true; 3965 3966 case OR_Ambiguous: 3967 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 3968 << "operator->" << BasePtr->getSourceRange(); 3969 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3970 return true; 3971 3972 case OR_Deleted: 3973 Diag(OpLoc, diag::err_ovl_deleted_oper) 3974 << Best->Function->isDeleted() 3975 << "operator->" << BasePtr->getSourceRange(); 3976 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3977 return true; 3978 } 3979 3980 // Convert the object parameter. 3981 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3982 if (PerformObjectArgumentInitialization(Base, Method)) 3983 return true; 3984 3985 // No concerns about early exits now. 3986 BasePtr.take(); 3987 3988 // Build the operator call. 3989 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(), 3990 SourceLocation()); 3991 UsualUnaryConversions(FnExpr); 3992 Base = new (Context) CXXOperatorCallExpr(Context, FnExpr, &Base, 1, 3993 Method->getResultType().getNonReferenceType(), 3994 OpLoc); 3995 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow, 3996 MemberLoc, Member).release(); 3997} 3998 3999/// FixOverloadedFunctionReference - E is an expression that refers to 4000/// a C++ overloaded function (possibly with some parentheses and 4001/// perhaps a '&' around it). We have resolved the overloaded function 4002/// to the function declaration Fn, so patch up the expression E to 4003/// refer (possibly indirectly) to Fn. 4004void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 4005 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 4006 FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 4007 E->setType(PE->getSubExpr()->getType()); 4008 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 4009 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 4010 "Can only take the address of an overloaded function"); 4011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 4012 if (Method->isStatic()) { 4013 // Do nothing: static member functions aren't any different 4014 // from non-member functions. 4015 } 4016 else if (QualifiedDeclRefExpr *DRE 4017 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) { 4018 // We have taken the address of a pointer to member 4019 // function. Perform the computation here so that we get the 4020 // appropriate pointer to member type. 4021 DRE->setDecl(Fn); 4022 DRE->setType(Fn->getType()); 4023 QualType ClassType 4024 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 4025 E->setType(Context.getMemberPointerType(Fn->getType(), 4026 ClassType.getTypePtr())); 4027 return; 4028 } 4029 } 4030 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 4031 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType())); 4032 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 4033 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) && 4034 "Expected overloaded function"); 4035 DR->setDecl(Fn); 4036 E->setType(Fn->getType()); 4037 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) { 4038 MemExpr->setMemberDecl(Fn); 4039 E->setType(Fn->getType()); 4040 } else { 4041 assert(false && "Invalid reference to overloaded function"); 4042 } 4043} 4044 4045} // end namespace clang 4046