SemaExpr.cpp revision 263508
1254721Semaste//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2254721Semaste// 3353358Sdim// The LLVM Compiler Infrastructure 4353358Sdim// 5353358Sdim// This file is distributed under the University of Illinois Open Source 6254721Semaste// License. See LICENSE.TXT for details. 7254721Semaste// 8254721Semaste//===----------------------------------------------------------------------===// 9254721Semaste// 10254721Semaste// This file implements semantic analysis for expressions. 11254721Semaste// 12254721Semaste//===----------------------------------------------------------------------===// 13254721Semaste 14254721Semaste#include "clang/Sema/SemaInternal.h" 15314564Sdim#include "TreeTransform.h" 16314564Sdim#include "clang/AST/ASTConsumer.h" 17314564Sdim#include "clang/AST/ASTContext.h" 18314564Sdim#include "clang/AST/ASTLambda.h" 19254721Semaste#include "clang/AST/ASTMutationListener.h" 20314564Sdim#include "clang/AST/CXXInheritance.h" 21314564Sdim#include "clang/AST/DeclObjC.h" 22314564Sdim#include "clang/AST/DeclTemplate.h" 23314564Sdim#include "clang/AST/EvaluatedExprVisitor.h" 24314564Sdim#include "clang/AST/Expr.h" 25314564Sdim#include "clang/AST/ExprCXX.h" 26314564Sdim#include "clang/AST/ExprObjC.h" 27314564Sdim#include "clang/AST/RecursiveASTVisitor.h" 28314564Sdim#include "clang/AST/TypeLoc.h" 29314564Sdim#include "clang/Basic/PartialDiagnostic.h" 30314564Sdim#include "clang/Basic/SourceManager.h" 31314564Sdim#include "clang/Basic/TargetInfo.h" 32314564Sdim#include "clang/Lex/LiteralSupport.h" 33314564Sdim#include "clang/Lex/Preprocessor.h" 34314564Sdim#include "clang/Sema/AnalysisBasedWarnings.h" 35314564Sdim#include "clang/Sema/DeclSpec.h" 36314564Sdim#include "clang/Sema/DelayedDiagnostic.h" 37314564Sdim#include "clang/Sema/Designator.h" 38314564Sdim#include "clang/Sema/Initialization.h" 39314564Sdim#include "clang/Sema/Lookup.h" 40314564Sdim#include "clang/Sema/ParsedTemplate.h" 41314564Sdim#include "clang/Sema/Scope.h" 42314564Sdim#include "clang/Sema/ScopeInfo.h" 43314564Sdim#include "clang/Sema/SemaFixItUtils.h" 44314564Sdim#include "clang/Sema/Template.h" 45314564Sdimusing namespace clang; 46314564Sdimusing namespace sema; 47314564Sdim 48314564Sdim/// \brief Determine whether the use of this declaration is valid, without 49314564Sdim/// emitting diagnostics. 50314564Sdimbool Sema::CanUseDecl(NamedDecl *D) { 51314564Sdim // See if this is an auto-typed variable whose initializer we are parsing. 52314564Sdim if (ParsingInitForAutoVars.count(D)) 53314564Sdim return false; 54314564Sdim 55314564Sdim // See if this is a deleted function. 56314564Sdim if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 57314564Sdim if (FD->isDeleted()) 58314564Sdim return false; 59314564Sdim 60314564Sdim // If the function has a deduced return type, and we can't deduce it, 61314564Sdim // then we can't use it either. 62314564Sdim if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 63314564Sdim DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false)) 64314564Sdim return false; 65314564Sdim } 66314564Sdim 67314564Sdim // See if this function is unavailable. 68314564Sdim if (D->getAvailability() == AR_Unavailable && 69314564Sdim cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 70314564Sdim return false; 71314564Sdim 72314564Sdim return true; 73314564Sdim} 74314564Sdim 75314564Sdimstatic void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 76314564Sdim // Warn if this is used but marked unused. 77314564Sdim if (D->hasAttr<UnusedAttr>()) { 78314564Sdim const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 79314564Sdim if (!DC->hasAttr<UnusedAttr>()) 80314564Sdim S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 81314564Sdim } 82314564Sdim} 83314564Sdim 84314564Sdimstatic AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 85314564Sdim NamedDecl *D, SourceLocation Loc, 86314564Sdim const ObjCInterfaceDecl *UnknownObjCClass) { 87314564Sdim // See if this declaration is unavailable or deprecated. 88314564Sdim std::string Message; 89314564Sdim AvailabilityResult Result = D->getAvailability(&Message); 90314564Sdim if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 91314564Sdim if (Result == AR_Available) { 92314564Sdim const DeclContext *DC = ECD->getDeclContext(); 93314564Sdim if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 94314564Sdim Result = TheEnumDecl->getAvailability(&Message); 95314564Sdim } 96314564Sdim 97314564Sdim const ObjCPropertyDecl *ObjCPDecl = 0; 98314564Sdim if (Result == AR_Deprecated || Result == AR_Unavailable) { 99314564Sdim if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 100314564Sdim if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 101314564Sdim AvailabilityResult PDeclResult = PD->getAvailability(0); 102314564Sdim if (PDeclResult == Result) 103314564Sdim ObjCPDecl = PD; 104314564Sdim } 105314564Sdim } 106314564Sdim } 107314564Sdim 108314564Sdim switch (Result) { 109314564Sdim case AR_Available: 110314564Sdim case AR_NotYetIntroduced: 111314564Sdim break; 112314564Sdim 113314564Sdim case AR_Deprecated: 114314564Sdim S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 115314564Sdim break; 116314564Sdim 117314564Sdim case AR_Unavailable: 118314564Sdim if (S.getCurContextAvailability() != AR_Unavailable) { 119314564Sdim if (Message.empty()) { 120314564Sdim if (!UnknownObjCClass) { 121314564Sdim S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 122314564Sdim if (ObjCPDecl) 123254721Semaste S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 124254721Semaste << ObjCPDecl->getDeclName() << 1; 125314564Sdim } 126314564Sdim else 127314564Sdim S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 128314564Sdim << D->getDeclName(); 129314564Sdim } 130254721Semaste else 131254721Semaste S.Diag(Loc, diag::err_unavailable_message) 132314564Sdim << D->getDeclName() << Message; 133314564Sdim S.Diag(D->getLocation(), diag::note_unavailable_here) 134 << isa<FunctionDecl>(D) << false; 135 if (ObjCPDecl) 136 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 137 << ObjCPDecl->getDeclName() << 1; 138 } 139 break; 140 } 141 return Result; 142} 143 144/// \brief Emit a note explaining that this function is deleted. 145void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 146 assert(Decl->isDeleted()); 147 148 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 149 150 if (Method && Method->isDeleted() && Method->isDefaulted()) { 151 // If the method was explicitly defaulted, point at that declaration. 152 if (!Method->isImplicit()) 153 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 154 155 // Try to diagnose why this special member function was implicitly 156 // deleted. This might fail, if that reason no longer applies. 157 CXXSpecialMember CSM = getSpecialMember(Method); 158 if (CSM != CXXInvalid) 159 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 160 161 return; 162 } 163 164 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 165 if (CXXConstructorDecl *BaseCD = 166 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 167 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 168 if (BaseCD->isDeleted()) { 169 NoteDeletedFunction(BaseCD); 170 } else { 171 // FIXME: An explanation of why exactly it can't be inherited 172 // would be nice. 173 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 174 } 175 return; 176 } 177 } 178 179 Diag(Decl->getLocation(), diag::note_unavailable_here) 180 << 1 << true; 181} 182 183/// \brief Determine whether a FunctionDecl was ever declared with an 184/// explicit storage class. 185static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 186 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 187 E = D->redecls_end(); 188 I != E; ++I) { 189 if (I->getStorageClass() != SC_None) 190 return true; 191 } 192 return false; 193} 194 195/// \brief Check whether we're in an extern inline function and referring to a 196/// variable or function with internal linkage (C11 6.7.4p3). 197/// 198/// This is only a warning because we used to silently accept this code, but 199/// in many cases it will not behave correctly. This is not enabled in C++ mode 200/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 201/// and so while there may still be user mistakes, most of the time we can't 202/// prove that there are errors. 203static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 204 const NamedDecl *D, 205 SourceLocation Loc) { 206 // This is disabled under C++; there are too many ways for this to fire in 207 // contexts where the warning is a false positive, or where it is technically 208 // correct but benign. 209 if (S.getLangOpts().CPlusPlus) 210 return; 211 212 // Check if this is an inlined function or method. 213 FunctionDecl *Current = S.getCurFunctionDecl(); 214 if (!Current) 215 return; 216 if (!Current->isInlined()) 217 return; 218 if (!Current->isExternallyVisible()) 219 return; 220 221 // Check if the decl has internal linkage. 222 if (D->getFormalLinkage() != InternalLinkage) 223 return; 224 225 // Downgrade from ExtWarn to Extension if 226 // (1) the supposedly external inline function is in the main file, 227 // and probably won't be included anywhere else. 228 // (2) the thing we're referencing is a pure function. 229 // (3) the thing we're referencing is another inline function. 230 // This last can give us false negatives, but it's better than warning on 231 // wrappers for simple C library functions. 232 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 233 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 234 if (!DowngradeWarning && UsedFn) 235 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 236 237 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 238 : diag::warn_internal_in_extern_inline) 239 << /*IsVar=*/!UsedFn << D; 240 241 S.MaybeSuggestAddingStaticToDecl(Current); 242 243 S.Diag(D->getCanonicalDecl()->getLocation(), 244 diag::note_internal_decl_declared_here) 245 << D; 246} 247 248void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 249 const FunctionDecl *First = Cur->getFirstDecl(); 250 251 // Suggest "static" on the function, if possible. 252 if (!hasAnyExplicitStorageClass(First)) { 253 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 254 Diag(DeclBegin, diag::note_convert_inline_to_static) 255 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 256 } 257} 258 259/// \brief Determine whether the use of this declaration is valid, and 260/// emit any corresponding diagnostics. 261/// 262/// This routine diagnoses various problems with referencing 263/// declarations that can occur when using a declaration. For example, 264/// it might warn if a deprecated or unavailable declaration is being 265/// used, or produce an error (and return true) if a C++0x deleted 266/// function is being used. 267/// 268/// \returns true if there was an error (this declaration cannot be 269/// referenced), false otherwise. 270/// 271bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 272 const ObjCInterfaceDecl *UnknownObjCClass) { 273 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 274 // If there were any diagnostics suppressed by template argument deduction, 275 // emit them now. 276 SuppressedDiagnosticsMap::iterator 277 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 278 if (Pos != SuppressedDiagnostics.end()) { 279 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 280 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 281 Diag(Suppressed[I].first, Suppressed[I].second); 282 283 // Clear out the list of suppressed diagnostics, so that we don't emit 284 // them again for this specialization. However, we don't obsolete this 285 // entry from the table, because we want to avoid ever emitting these 286 // diagnostics again. 287 Suppressed.clear(); 288 } 289 } 290 291 // See if this is an auto-typed variable whose initializer we are parsing. 292 if (ParsingInitForAutoVars.count(D)) { 293 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 294 << D->getDeclName(); 295 return true; 296 } 297 298 // See if this is a deleted function. 299 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 300 if (FD->isDeleted()) { 301 Diag(Loc, diag::err_deleted_function_use); 302 NoteDeletedFunction(FD); 303 return true; 304 } 305 306 // If the function has a deduced return type, and we can't deduce it, 307 // then we can't use it either. 308 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 309 DeduceReturnType(FD, Loc)) 310 return true; 311 } 312 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 313 314 DiagnoseUnusedOfDecl(*this, D, Loc); 315 316 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 317 318 return false; 319} 320 321/// \brief Retrieve the message suffix that should be added to a 322/// diagnostic complaining about the given function being deleted or 323/// unavailable. 324std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 325 std::string Message; 326 if (FD->getAvailability(&Message)) 327 return ": " + Message; 328 329 return std::string(); 330} 331 332/// DiagnoseSentinelCalls - This routine checks whether a call or 333/// message-send is to a declaration with the sentinel attribute, and 334/// if so, it checks that the requirements of the sentinel are 335/// satisfied. 336void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 337 ArrayRef<Expr *> Args) { 338 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 339 if (!attr) 340 return; 341 342 // The number of formal parameters of the declaration. 343 unsigned numFormalParams; 344 345 // The kind of declaration. This is also an index into a %select in 346 // the diagnostic. 347 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 348 349 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 350 numFormalParams = MD->param_size(); 351 calleeType = CT_Method; 352 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 353 numFormalParams = FD->param_size(); 354 calleeType = CT_Function; 355 } else if (isa<VarDecl>(D)) { 356 QualType type = cast<ValueDecl>(D)->getType(); 357 const FunctionType *fn = 0; 358 if (const PointerType *ptr = type->getAs<PointerType>()) { 359 fn = ptr->getPointeeType()->getAs<FunctionType>(); 360 if (!fn) return; 361 calleeType = CT_Function; 362 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 363 fn = ptr->getPointeeType()->castAs<FunctionType>(); 364 calleeType = CT_Block; 365 } else { 366 return; 367 } 368 369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 370 numFormalParams = proto->getNumArgs(); 371 } else { 372 numFormalParams = 0; 373 } 374 } else { 375 return; 376 } 377 378 // "nullPos" is the number of formal parameters at the end which 379 // effectively count as part of the variadic arguments. This is 380 // useful if you would prefer to not have *any* formal parameters, 381 // but the language forces you to have at least one. 382 unsigned nullPos = attr->getNullPos(); 383 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 384 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 385 386 // The number of arguments which should follow the sentinel. 387 unsigned numArgsAfterSentinel = attr->getSentinel(); 388 389 // If there aren't enough arguments for all the formal parameters, 390 // the sentinel, and the args after the sentinel, complain. 391 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 392 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 393 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 394 return; 395 } 396 397 // Otherwise, find the sentinel expression. 398 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 399 if (!sentinelExpr) return; 400 if (sentinelExpr->isValueDependent()) return; 401 if (Context.isSentinelNullExpr(sentinelExpr)) return; 402 403 // Pick a reasonable string to insert. Optimistically use 'nil' or 404 // 'NULL' if those are actually defined in the context. Only use 405 // 'nil' for ObjC methods, where it's much more likely that the 406 // variadic arguments form a list of object pointers. 407 SourceLocation MissingNilLoc 408 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 409 std::string NullValue; 410 if (calleeType == CT_Method && 411 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 412 NullValue = "nil"; 413 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 414 NullValue = "NULL"; 415 else 416 NullValue = "(void*) 0"; 417 418 if (MissingNilLoc.isInvalid()) 419 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 420 else 421 Diag(MissingNilLoc, diag::warn_missing_sentinel) 422 << int(calleeType) 423 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 424 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 425} 426 427SourceRange Sema::getExprRange(Expr *E) const { 428 return E ? E->getSourceRange() : SourceRange(); 429} 430 431//===----------------------------------------------------------------------===// 432// Standard Promotions and Conversions 433//===----------------------------------------------------------------------===// 434 435/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 436ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 437 // Handle any placeholder expressions which made it here. 438 if (E->getType()->isPlaceholderType()) { 439 ExprResult result = CheckPlaceholderExpr(E); 440 if (result.isInvalid()) return ExprError(); 441 E = result.take(); 442 } 443 444 QualType Ty = E->getType(); 445 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 446 447 if (Ty->isFunctionType()) 448 E = ImpCastExprToType(E, Context.getPointerType(Ty), 449 CK_FunctionToPointerDecay).take(); 450 else if (Ty->isArrayType()) { 451 // In C90 mode, arrays only promote to pointers if the array expression is 452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 453 // type 'array of type' is converted to an expression that has type 'pointer 454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 455 // that has type 'array of type' ...". The relevant change is "an lvalue" 456 // (C90) to "an expression" (C99). 457 // 458 // C++ 4.2p1: 459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 460 // T" can be converted to an rvalue of type "pointer to T". 461 // 462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 464 CK_ArrayToPointerDecay).take(); 465 } 466 return Owned(E); 467} 468 469static void CheckForNullPointerDereference(Sema &S, Expr *E) { 470 // Check to see if we are dereferencing a null pointer. If so, 471 // and if not volatile-qualified, this is undefined behavior that the 472 // optimizer will delete, so warn about it. People sometimes try to use this 473 // to get a deterministic trap and are surprised by clang's behavior. This 474 // only handles the pattern "*null", which is a very syntactic check. 475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 476 if (UO->getOpcode() == UO_Deref && 477 UO->getSubExpr()->IgnoreParenCasts()-> 478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 479 !UO->getType().isVolatileQualified()) { 480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 481 S.PDiag(diag::warn_indirection_through_null) 482 << UO->getSubExpr()->getSourceRange()); 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::note_indirection_through_null)); 485 } 486} 487 488static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 489 SourceLocation AssignLoc, 490 const Expr* RHS) { 491 const ObjCIvarDecl *IV = OIRE->getDecl(); 492 if (!IV) 493 return; 494 495 DeclarationName MemberName = IV->getDeclName(); 496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 497 if (!Member || !Member->isStr("isa")) 498 return; 499 500 const Expr *Base = OIRE->getBase(); 501 QualType BaseType = Base->getType(); 502 if (OIRE->isArrow()) 503 BaseType = BaseType->getPointeeType(); 504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 506 ObjCInterfaceDecl *ClassDeclared = 0; 507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 508 if (!ClassDeclared->getSuperClass() 509 && (*ClassDeclared->ivar_begin()) == IV) { 510 if (RHS) { 511 NamedDecl *ObjectSetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_setClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectSetClass) { 516 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 518 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 519 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 520 AssignLoc), ",") << 521 FixItHint::CreateInsertion(RHSLocEnd, ")"); 522 } 523 else 524 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 525 } else { 526 NamedDecl *ObjectGetClass = 527 S.LookupSingleName(S.TUScope, 528 &S.Context.Idents.get("object_getClass"), 529 SourceLocation(), S.LookupOrdinaryName); 530 if (ObjectGetClass) 531 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 532 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 533 FixItHint::CreateReplacement( 534 SourceRange(OIRE->getOpLoc(), 535 OIRE->getLocEnd()), ")"); 536 else 537 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 538 } 539 S.Diag(IV->getLocation(), diag::note_ivar_decl); 540 } 541 } 542} 543 544ExprResult Sema::DefaultLvalueConversion(Expr *E) { 545 // Handle any placeholder expressions which made it here. 546 if (E->getType()->isPlaceholderType()) { 547 ExprResult result = CheckPlaceholderExpr(E); 548 if (result.isInvalid()) return ExprError(); 549 E = result.take(); 550 } 551 552 // C++ [conv.lval]p1: 553 // A glvalue of a non-function, non-array type T can be 554 // converted to a prvalue. 555 if (!E->isGLValue()) return Owned(E); 556 557 QualType T = E->getType(); 558 assert(!T.isNull() && "r-value conversion on typeless expression?"); 559 560 // We don't want to throw lvalue-to-rvalue casts on top of 561 // expressions of certain types in C++. 562 if (getLangOpts().CPlusPlus && 563 (E->getType() == Context.OverloadTy || 564 T->isDependentType() || 565 T->isRecordType())) 566 return Owned(E); 567 568 // The C standard is actually really unclear on this point, and 569 // DR106 tells us what the result should be but not why. It's 570 // generally best to say that void types just doesn't undergo 571 // lvalue-to-rvalue at all. Note that expressions of unqualified 572 // 'void' type are never l-values, but qualified void can be. 573 if (T->isVoidType()) 574 return Owned(E); 575 576 // OpenCL usually rejects direct accesses to values of 'half' type. 577 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 578 T->isHalfType()) { 579 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 580 << 0 << T; 581 return ExprError(); 582 } 583 584 CheckForNullPointerDereference(*this, E); 585 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 586 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 587 &Context.Idents.get("object_getClass"), 588 SourceLocation(), LookupOrdinaryName); 589 if (ObjectGetClass) 590 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 591 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 592 FixItHint::CreateReplacement( 593 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 594 else 595 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 596 } 597 else if (const ObjCIvarRefExpr *OIRE = 598 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 599 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 600 601 // C++ [conv.lval]p1: 602 // [...] If T is a non-class type, the type of the prvalue is the 603 // cv-unqualified version of T. Otherwise, the type of the 604 // rvalue is T. 605 // 606 // C99 6.3.2.1p2: 607 // If the lvalue has qualified type, the value has the unqualified 608 // version of the type of the lvalue; otherwise, the value has the 609 // type of the lvalue. 610 if (T.hasQualifiers()) 611 T = T.getUnqualifiedType(); 612 613 UpdateMarkingForLValueToRValue(E); 614 615 // Loading a __weak object implicitly retains the value, so we need a cleanup to 616 // balance that. 617 if (getLangOpts().ObjCAutoRefCount && 618 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 619 ExprNeedsCleanups = true; 620 621 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 622 E, 0, VK_RValue)); 623 624 // C11 6.3.2.1p2: 625 // ... if the lvalue has atomic type, the value has the non-atomic version 626 // of the type of the lvalue ... 627 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 628 T = Atomic->getValueType().getUnqualifiedType(); 629 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 630 Res.get(), 0, VK_RValue)); 631 } 632 633 return Res; 634} 635 636ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 637 ExprResult Res = DefaultFunctionArrayConversion(E); 638 if (Res.isInvalid()) 639 return ExprError(); 640 Res = DefaultLvalueConversion(Res.take()); 641 if (Res.isInvalid()) 642 return ExprError(); 643 return Res; 644} 645 646 647/// UsualUnaryConversions - Performs various conversions that are common to most 648/// operators (C99 6.3). The conversions of array and function types are 649/// sometimes suppressed. For example, the array->pointer conversion doesn't 650/// apply if the array is an argument to the sizeof or address (&) operators. 651/// In these instances, this routine should *not* be called. 652ExprResult Sema::UsualUnaryConversions(Expr *E) { 653 // First, convert to an r-value. 654 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 655 if (Res.isInvalid()) 656 return ExprError(); 657 E = Res.take(); 658 659 QualType Ty = E->getType(); 660 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 661 662 // Half FP have to be promoted to float unless it is natively supported 663 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 664 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 665 666 // Try to perform integral promotions if the object has a theoretically 667 // promotable type. 668 if (Ty->isIntegralOrUnscopedEnumerationType()) { 669 // C99 6.3.1.1p2: 670 // 671 // The following may be used in an expression wherever an int or 672 // unsigned int may be used: 673 // - an object or expression with an integer type whose integer 674 // conversion rank is less than or equal to the rank of int 675 // and unsigned int. 676 // - A bit-field of type _Bool, int, signed int, or unsigned int. 677 // 678 // If an int can represent all values of the original type, the 679 // value is converted to an int; otherwise, it is converted to an 680 // unsigned int. These are called the integer promotions. All 681 // other types are unchanged by the integer promotions. 682 683 QualType PTy = Context.isPromotableBitField(E); 684 if (!PTy.isNull()) { 685 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 686 return Owned(E); 687 } 688 if (Ty->isPromotableIntegerType()) { 689 QualType PT = Context.getPromotedIntegerType(Ty); 690 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 691 return Owned(E); 692 } 693 } 694 return Owned(E); 695} 696 697/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 698/// do not have a prototype. Arguments that have type float or __fp16 699/// are promoted to double. All other argument types are converted by 700/// UsualUnaryConversions(). 701ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 702 QualType Ty = E->getType(); 703 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 704 705 ExprResult Res = UsualUnaryConversions(E); 706 if (Res.isInvalid()) 707 return ExprError(); 708 E = Res.take(); 709 710 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 711 // double. 712 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 713 if (BTy && (BTy->getKind() == BuiltinType::Half || 714 BTy->getKind() == BuiltinType::Float)) 715 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 716 717 // C++ performs lvalue-to-rvalue conversion as a default argument 718 // promotion, even on class types, but note: 719 // C++11 [conv.lval]p2: 720 // When an lvalue-to-rvalue conversion occurs in an unevaluated 721 // operand or a subexpression thereof the value contained in the 722 // referenced object is not accessed. Otherwise, if the glvalue 723 // has a class type, the conversion copy-initializes a temporary 724 // of type T from the glvalue and the result of the conversion 725 // is a prvalue for the temporary. 726 // FIXME: add some way to gate this entire thing for correctness in 727 // potentially potentially evaluated contexts. 728 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 729 ExprResult Temp = PerformCopyInitialization( 730 InitializedEntity::InitializeTemporary(E->getType()), 731 E->getExprLoc(), 732 Owned(E)); 733 if (Temp.isInvalid()) 734 return ExprError(); 735 E = Temp.get(); 736 } 737 738 return Owned(E); 739} 740 741/// Determine the degree of POD-ness for an expression. 742/// Incomplete types are considered POD, since this check can be performed 743/// when we're in an unevaluated context. 744Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 745 if (Ty->isIncompleteType()) { 746 // C++11 [expr.call]p7: 747 // After these conversions, if the argument does not have arithmetic, 748 // enumeration, pointer, pointer to member, or class type, the program 749 // is ill-formed. 750 // 751 // Since we've already performed array-to-pointer and function-to-pointer 752 // decay, the only such type in C++ is cv void. This also handles 753 // initializer lists as variadic arguments. 754 if (Ty->isVoidType()) 755 return VAK_Invalid; 756 757 if (Ty->isObjCObjectType()) 758 return VAK_Invalid; 759 return VAK_Valid; 760 } 761 762 if (Ty.isCXX98PODType(Context)) 763 return VAK_Valid; 764 765 // C++11 [expr.call]p7: 766 // Passing a potentially-evaluated argument of class type (Clause 9) 767 // having a non-trivial copy constructor, a non-trivial move constructor, 768 // or a non-trivial destructor, with no corresponding parameter, 769 // is conditionally-supported with implementation-defined semantics. 770 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 771 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 772 if (!Record->hasNonTrivialCopyConstructor() && 773 !Record->hasNonTrivialMoveConstructor() && 774 !Record->hasNonTrivialDestructor()) 775 return VAK_ValidInCXX11; 776 777 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 778 return VAK_Valid; 779 780 if (Ty->isObjCObjectType()) 781 return VAK_Invalid; 782 783 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 784 // permitted to reject them. We should consider doing so. 785 return VAK_Undefined; 786} 787 788void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 789 // Don't allow one to pass an Objective-C interface to a vararg. 790 const QualType &Ty = E->getType(); 791 VarArgKind VAK = isValidVarArgType(Ty); 792 793 // Complain about passing non-POD types through varargs. 794 switch (VAK) { 795 case VAK_Valid: 796 break; 797 798 case VAK_ValidInCXX11: 799 DiagRuntimeBehavior( 800 E->getLocStart(), 0, 801 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 802 << E->getType() << CT); 803 break; 804 805 case VAK_Undefined: 806 DiagRuntimeBehavior( 807 E->getLocStart(), 0, 808 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 809 << getLangOpts().CPlusPlus11 << Ty << CT); 810 break; 811 812 case VAK_Invalid: 813 if (Ty->isObjCObjectType()) 814 DiagRuntimeBehavior( 815 E->getLocStart(), 0, 816 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 817 << Ty << CT); 818 else 819 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 820 << isa<InitListExpr>(E) << Ty << CT; 821 break; 822 } 823} 824 825/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 826/// will create a trap if the resulting type is not a POD type. 827ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 828 FunctionDecl *FDecl) { 829 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 830 // Strip the unbridged-cast placeholder expression off, if applicable. 831 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 832 (CT == VariadicMethod || 833 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 834 E = stripARCUnbridgedCast(E); 835 836 // Otherwise, do normal placeholder checking. 837 } else { 838 ExprResult ExprRes = CheckPlaceholderExpr(E); 839 if (ExprRes.isInvalid()) 840 return ExprError(); 841 E = ExprRes.take(); 842 } 843 } 844 845 ExprResult ExprRes = DefaultArgumentPromotion(E); 846 if (ExprRes.isInvalid()) 847 return ExprError(); 848 E = ExprRes.take(); 849 850 // Diagnostics regarding non-POD argument types are 851 // emitted along with format string checking in Sema::CheckFunctionCall(). 852 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 853 // Turn this into a trap. 854 CXXScopeSpec SS; 855 SourceLocation TemplateKWLoc; 856 UnqualifiedId Name; 857 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 858 E->getLocStart()); 859 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 860 Name, true, false); 861 if (TrapFn.isInvalid()) 862 return ExprError(); 863 864 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 865 E->getLocStart(), None, 866 E->getLocEnd()); 867 if (Call.isInvalid()) 868 return ExprError(); 869 870 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 871 Call.get(), E); 872 if (Comma.isInvalid()) 873 return ExprError(); 874 return Comma.get(); 875 } 876 877 if (!getLangOpts().CPlusPlus && 878 RequireCompleteType(E->getExprLoc(), E->getType(), 879 diag::err_call_incomplete_argument)) 880 return ExprError(); 881 882 return Owned(E); 883} 884 885/// \brief Converts an integer to complex float type. Helper function of 886/// UsualArithmeticConversions() 887/// 888/// \return false if the integer expression is an integer type and is 889/// successfully converted to the complex type. 890static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 891 ExprResult &ComplexExpr, 892 QualType IntTy, 893 QualType ComplexTy, 894 bool SkipCast) { 895 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 896 if (SkipCast) return false; 897 if (IntTy->isIntegerType()) { 898 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 899 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 900 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 901 CK_FloatingRealToComplex); 902 } else { 903 assert(IntTy->isComplexIntegerType()); 904 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 905 CK_IntegralComplexToFloatingComplex); 906 } 907 return false; 908} 909 910/// \brief Takes two complex float types and converts them to the same type. 911/// Helper function of UsualArithmeticConversions() 912static QualType 913handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 914 ExprResult &RHS, QualType LHSType, 915 QualType RHSType, 916 bool IsCompAssign) { 917 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 918 919 if (order < 0) { 920 // _Complex float -> _Complex double 921 if (!IsCompAssign) 922 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 923 return RHSType; 924 } 925 if (order > 0) 926 // _Complex float -> _Complex double 927 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 928 return LHSType; 929} 930 931/// \brief Converts otherExpr to complex float and promotes complexExpr if 932/// necessary. Helper function of UsualArithmeticConversions() 933static QualType handleOtherComplexFloatConversion(Sema &S, 934 ExprResult &ComplexExpr, 935 ExprResult &OtherExpr, 936 QualType ComplexTy, 937 QualType OtherTy, 938 bool ConvertComplexExpr, 939 bool ConvertOtherExpr) { 940 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 941 942 // If just the complexExpr is complex, the otherExpr needs to be converted, 943 // and the complexExpr might need to be promoted. 944 if (order > 0) { // complexExpr is wider 945 // float -> _Complex double 946 if (ConvertOtherExpr) { 947 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 948 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 949 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 950 CK_FloatingRealToComplex); 951 } 952 return ComplexTy; 953 } 954 955 // otherTy is at least as wide. Find its corresponding complex type. 956 QualType result = (order == 0 ? ComplexTy : 957 S.Context.getComplexType(OtherTy)); 958 959 // double -> _Complex double 960 if (ConvertOtherExpr) 961 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 962 CK_FloatingRealToComplex); 963 964 // _Complex float -> _Complex double 965 if (ConvertComplexExpr && order < 0) 966 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 967 CK_FloatingComplexCast); 968 969 return result; 970} 971 972/// \brief Handle arithmetic conversion with complex types. Helper function of 973/// UsualArithmeticConversions() 974static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 975 ExprResult &RHS, QualType LHSType, 976 QualType RHSType, 977 bool IsCompAssign) { 978 // if we have an integer operand, the result is the complex type. 979 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 980 /*skipCast*/false)) 981 return LHSType; 982 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 983 /*skipCast*/IsCompAssign)) 984 return RHSType; 985 986 // This handles complex/complex, complex/float, or float/complex. 987 // When both operands are complex, the shorter operand is converted to the 988 // type of the longer, and that is the type of the result. This corresponds 989 // to what is done when combining two real floating-point operands. 990 // The fun begins when size promotion occur across type domains. 991 // From H&S 6.3.4: When one operand is complex and the other is a real 992 // floating-point type, the less precise type is converted, within it's 993 // real or complex domain, to the precision of the other type. For example, 994 // when combining a "long double" with a "double _Complex", the 995 // "double _Complex" is promoted to "long double _Complex". 996 997 bool LHSComplexFloat = LHSType->isComplexType(); 998 bool RHSComplexFloat = RHSType->isComplexType(); 999 1000 // If both are complex, just cast to the more precise type. 1001 if (LHSComplexFloat && RHSComplexFloat) 1002 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1003 LHSType, RHSType, 1004 IsCompAssign); 1005 1006 // If only one operand is complex, promote it if necessary and convert the 1007 // other operand to complex. 1008 if (LHSComplexFloat) 1009 return handleOtherComplexFloatConversion( 1010 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1011 /*convertOtherExpr*/ true); 1012 1013 assert(RHSComplexFloat); 1014 return handleOtherComplexFloatConversion( 1015 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1016 /*convertOtherExpr*/ !IsCompAssign); 1017} 1018 1019/// \brief Hande arithmetic conversion from integer to float. Helper function 1020/// of UsualArithmeticConversions() 1021static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1022 ExprResult &IntExpr, 1023 QualType FloatTy, QualType IntTy, 1024 bool ConvertFloat, bool ConvertInt) { 1025 if (IntTy->isIntegerType()) { 1026 if (ConvertInt) 1027 // Convert intExpr to the lhs floating point type. 1028 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1029 CK_IntegralToFloating); 1030 return FloatTy; 1031 } 1032 1033 // Convert both sides to the appropriate complex float. 1034 assert(IntTy->isComplexIntegerType()); 1035 QualType result = S.Context.getComplexType(FloatTy); 1036 1037 // _Complex int -> _Complex float 1038 if (ConvertInt) 1039 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1040 CK_IntegralComplexToFloatingComplex); 1041 1042 // float -> _Complex float 1043 if (ConvertFloat) 1044 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1045 CK_FloatingRealToComplex); 1046 1047 return result; 1048} 1049 1050/// \brief Handle arithmethic conversion with floating point types. Helper 1051/// function of UsualArithmeticConversions() 1052static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1053 ExprResult &RHS, QualType LHSType, 1054 QualType RHSType, bool IsCompAssign) { 1055 bool LHSFloat = LHSType->isRealFloatingType(); 1056 bool RHSFloat = RHSType->isRealFloatingType(); 1057 1058 // If we have two real floating types, convert the smaller operand 1059 // to the bigger result. 1060 if (LHSFloat && RHSFloat) { 1061 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1062 if (order > 0) { 1063 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1064 return LHSType; 1065 } 1066 1067 assert(order < 0 && "illegal float comparison"); 1068 if (!IsCompAssign) 1069 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1070 return RHSType; 1071 } 1072 1073 if (LHSFloat) 1074 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1075 /*convertFloat=*/!IsCompAssign, 1076 /*convertInt=*/ true); 1077 assert(RHSFloat); 1078 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1079 /*convertInt=*/ true, 1080 /*convertFloat=*/!IsCompAssign); 1081} 1082 1083typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1084 1085namespace { 1086/// These helper callbacks are placed in an anonymous namespace to 1087/// permit their use as function template parameters. 1088ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1089 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1090} 1091 1092ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1093 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1094 CK_IntegralComplexCast); 1095} 1096} 1097 1098/// \brief Handle integer arithmetic conversions. Helper function of 1099/// UsualArithmeticConversions() 1100template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1101static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1102 ExprResult &RHS, QualType LHSType, 1103 QualType RHSType, bool IsCompAssign) { 1104 // The rules for this case are in C99 6.3.1.8 1105 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1106 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1107 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1108 if (LHSSigned == RHSSigned) { 1109 // Same signedness; use the higher-ranked type 1110 if (order >= 0) { 1111 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1112 return LHSType; 1113 } else if (!IsCompAssign) 1114 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1115 return RHSType; 1116 } else if (order != (LHSSigned ? 1 : -1)) { 1117 // The unsigned type has greater than or equal rank to the 1118 // signed type, so use the unsigned type 1119 if (RHSSigned) { 1120 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1121 return LHSType; 1122 } else if (!IsCompAssign) 1123 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1124 return RHSType; 1125 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1126 // The two types are different widths; if we are here, that 1127 // means the signed type is larger than the unsigned type, so 1128 // use the signed type. 1129 if (LHSSigned) { 1130 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1131 return LHSType; 1132 } else if (!IsCompAssign) 1133 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1134 return RHSType; 1135 } else { 1136 // The signed type is higher-ranked than the unsigned type, 1137 // but isn't actually any bigger (like unsigned int and long 1138 // on most 32-bit systems). Use the unsigned type corresponding 1139 // to the signed type. 1140 QualType result = 1141 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1142 RHS = (*doRHSCast)(S, RHS.take(), result); 1143 if (!IsCompAssign) 1144 LHS = (*doLHSCast)(S, LHS.take(), result); 1145 return result; 1146 } 1147} 1148 1149/// \brief Handle conversions with GCC complex int extension. Helper function 1150/// of UsualArithmeticConversions() 1151static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1152 ExprResult &RHS, QualType LHSType, 1153 QualType RHSType, 1154 bool IsCompAssign) { 1155 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1156 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1157 1158 if (LHSComplexInt && RHSComplexInt) { 1159 QualType LHSEltType = LHSComplexInt->getElementType(); 1160 QualType RHSEltType = RHSComplexInt->getElementType(); 1161 QualType ScalarType = 1162 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1163 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1164 1165 return S.Context.getComplexType(ScalarType); 1166 } 1167 1168 if (LHSComplexInt) { 1169 QualType LHSEltType = LHSComplexInt->getElementType(); 1170 QualType ScalarType = 1171 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1172 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1173 QualType ComplexType = S.Context.getComplexType(ScalarType); 1174 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1175 CK_IntegralRealToComplex); 1176 1177 return ComplexType; 1178 } 1179 1180 assert(RHSComplexInt); 1181 1182 QualType RHSEltType = RHSComplexInt->getElementType(); 1183 QualType ScalarType = 1184 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1185 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1186 QualType ComplexType = S.Context.getComplexType(ScalarType); 1187 1188 if (!IsCompAssign) 1189 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1190 CK_IntegralRealToComplex); 1191 return ComplexType; 1192} 1193 1194/// UsualArithmeticConversions - Performs various conversions that are common to 1195/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1196/// routine returns the first non-arithmetic type found. The client is 1197/// responsible for emitting appropriate error diagnostics. 1198QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1199 bool IsCompAssign) { 1200 if (!IsCompAssign) { 1201 LHS = UsualUnaryConversions(LHS.take()); 1202 if (LHS.isInvalid()) 1203 return QualType(); 1204 } 1205 1206 RHS = UsualUnaryConversions(RHS.take()); 1207 if (RHS.isInvalid()) 1208 return QualType(); 1209 1210 // For conversion purposes, we ignore any qualifiers. 1211 // For example, "const float" and "float" are equivalent. 1212 QualType LHSType = 1213 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1214 QualType RHSType = 1215 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1216 1217 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1218 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1219 LHSType = AtomicLHS->getValueType(); 1220 1221 // If both types are identical, no conversion is needed. 1222 if (LHSType == RHSType) 1223 return LHSType; 1224 1225 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1226 // The caller can deal with this (e.g. pointer + int). 1227 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1228 return QualType(); 1229 1230 // Apply unary and bitfield promotions to the LHS's type. 1231 QualType LHSUnpromotedType = LHSType; 1232 if (LHSType->isPromotableIntegerType()) 1233 LHSType = Context.getPromotedIntegerType(LHSType); 1234 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1235 if (!LHSBitfieldPromoteTy.isNull()) 1236 LHSType = LHSBitfieldPromoteTy; 1237 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1238 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1239 1240 // If both types are identical, no conversion is needed. 1241 if (LHSType == RHSType) 1242 return LHSType; 1243 1244 // At this point, we have two different arithmetic types. 1245 1246 // Handle complex types first (C99 6.3.1.8p1). 1247 if (LHSType->isComplexType() || RHSType->isComplexType()) 1248 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1249 IsCompAssign); 1250 1251 // Now handle "real" floating types (i.e. float, double, long double). 1252 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1253 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1254 IsCompAssign); 1255 1256 // Handle GCC complex int extension. 1257 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1258 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1259 IsCompAssign); 1260 1261 // Finally, we have two differing integer types. 1262 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1263 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1264} 1265 1266 1267//===----------------------------------------------------------------------===// 1268// Semantic Analysis for various Expression Types 1269//===----------------------------------------------------------------------===// 1270 1271 1272ExprResult 1273Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1274 SourceLocation DefaultLoc, 1275 SourceLocation RParenLoc, 1276 Expr *ControllingExpr, 1277 ArrayRef<ParsedType> ArgTypes, 1278 ArrayRef<Expr *> ArgExprs) { 1279 unsigned NumAssocs = ArgTypes.size(); 1280 assert(NumAssocs == ArgExprs.size()); 1281 1282 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1283 for (unsigned i = 0; i < NumAssocs; ++i) { 1284 if (ArgTypes[i]) 1285 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1286 else 1287 Types[i] = 0; 1288 } 1289 1290 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1291 ControllingExpr, 1292 llvm::makeArrayRef(Types, NumAssocs), 1293 ArgExprs); 1294 delete [] Types; 1295 return ER; 1296} 1297 1298ExprResult 1299Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1300 SourceLocation DefaultLoc, 1301 SourceLocation RParenLoc, 1302 Expr *ControllingExpr, 1303 ArrayRef<TypeSourceInfo *> Types, 1304 ArrayRef<Expr *> Exprs) { 1305 unsigned NumAssocs = Types.size(); 1306 assert(NumAssocs == Exprs.size()); 1307 if (ControllingExpr->getType()->isPlaceholderType()) { 1308 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1309 if (result.isInvalid()) return ExprError(); 1310 ControllingExpr = result.take(); 1311 } 1312 1313 bool TypeErrorFound = false, 1314 IsResultDependent = ControllingExpr->isTypeDependent(), 1315 ContainsUnexpandedParameterPack 1316 = ControllingExpr->containsUnexpandedParameterPack(); 1317 1318 for (unsigned i = 0; i < NumAssocs; ++i) { 1319 if (Exprs[i]->containsUnexpandedParameterPack()) 1320 ContainsUnexpandedParameterPack = true; 1321 1322 if (Types[i]) { 1323 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1324 ContainsUnexpandedParameterPack = true; 1325 1326 if (Types[i]->getType()->isDependentType()) { 1327 IsResultDependent = true; 1328 } else { 1329 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1330 // complete object type other than a variably modified type." 1331 unsigned D = 0; 1332 if (Types[i]->getType()->isIncompleteType()) 1333 D = diag::err_assoc_type_incomplete; 1334 else if (!Types[i]->getType()->isObjectType()) 1335 D = diag::err_assoc_type_nonobject; 1336 else if (Types[i]->getType()->isVariablyModifiedType()) 1337 D = diag::err_assoc_type_variably_modified; 1338 1339 if (D != 0) { 1340 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1341 << Types[i]->getTypeLoc().getSourceRange() 1342 << Types[i]->getType(); 1343 TypeErrorFound = true; 1344 } 1345 1346 // C11 6.5.1.1p2 "No two generic associations in the same generic 1347 // selection shall specify compatible types." 1348 for (unsigned j = i+1; j < NumAssocs; ++j) 1349 if (Types[j] && !Types[j]->getType()->isDependentType() && 1350 Context.typesAreCompatible(Types[i]->getType(), 1351 Types[j]->getType())) { 1352 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1353 diag::err_assoc_compatible_types) 1354 << Types[j]->getTypeLoc().getSourceRange() 1355 << Types[j]->getType() 1356 << Types[i]->getType(); 1357 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1358 diag::note_compat_assoc) 1359 << Types[i]->getTypeLoc().getSourceRange() 1360 << Types[i]->getType(); 1361 TypeErrorFound = true; 1362 } 1363 } 1364 } 1365 } 1366 if (TypeErrorFound) 1367 return ExprError(); 1368 1369 // If we determined that the generic selection is result-dependent, don't 1370 // try to compute the result expression. 1371 if (IsResultDependent) 1372 return Owned(new (Context) GenericSelectionExpr( 1373 Context, KeyLoc, ControllingExpr, 1374 Types, Exprs, 1375 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1376 1377 SmallVector<unsigned, 1> CompatIndices; 1378 unsigned DefaultIndex = -1U; 1379 for (unsigned i = 0; i < NumAssocs; ++i) { 1380 if (!Types[i]) 1381 DefaultIndex = i; 1382 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1383 Types[i]->getType())) 1384 CompatIndices.push_back(i); 1385 } 1386 1387 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1388 // type compatible with at most one of the types named in its generic 1389 // association list." 1390 if (CompatIndices.size() > 1) { 1391 // We strip parens here because the controlling expression is typically 1392 // parenthesized in macro definitions. 1393 ControllingExpr = ControllingExpr->IgnoreParens(); 1394 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1395 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1396 << (unsigned) CompatIndices.size(); 1397 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1398 E = CompatIndices.end(); I != E; ++I) { 1399 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1400 diag::note_compat_assoc) 1401 << Types[*I]->getTypeLoc().getSourceRange() 1402 << Types[*I]->getType(); 1403 } 1404 return ExprError(); 1405 } 1406 1407 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1408 // its controlling expression shall have type compatible with exactly one of 1409 // the types named in its generic association list." 1410 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1411 // We strip parens here because the controlling expression is typically 1412 // parenthesized in macro definitions. 1413 ControllingExpr = ControllingExpr->IgnoreParens(); 1414 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1415 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1416 return ExprError(); 1417 } 1418 1419 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1420 // type name that is compatible with the type of the controlling expression, 1421 // then the result expression of the generic selection is the expression 1422 // in that generic association. Otherwise, the result expression of the 1423 // generic selection is the expression in the default generic association." 1424 unsigned ResultIndex = 1425 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1426 1427 return Owned(new (Context) GenericSelectionExpr( 1428 Context, KeyLoc, ControllingExpr, 1429 Types, Exprs, 1430 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1431 ResultIndex)); 1432} 1433 1434/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1435/// location of the token and the offset of the ud-suffix within it. 1436static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1437 unsigned Offset) { 1438 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1439 S.getLangOpts()); 1440} 1441 1442/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1443/// the corresponding cooked (non-raw) literal operator, and build a call to it. 1444static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1445 IdentifierInfo *UDSuffix, 1446 SourceLocation UDSuffixLoc, 1447 ArrayRef<Expr*> Args, 1448 SourceLocation LitEndLoc) { 1449 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1450 1451 QualType ArgTy[2]; 1452 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1453 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1454 if (ArgTy[ArgIdx]->isArrayType()) 1455 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1456 } 1457 1458 DeclarationName OpName = 1459 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1460 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1461 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1462 1463 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1464 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1465 /*AllowRaw*/false, /*AllowTemplate*/false, 1466 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1467 return ExprError(); 1468 1469 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1470} 1471 1472/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1473/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1474/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1475/// multiple tokens. However, the common case is that StringToks points to one 1476/// string. 1477/// 1478ExprResult 1479Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1480 Scope *UDLScope) { 1481 assert(NumStringToks && "Must have at least one string!"); 1482 1483 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1484 if (Literal.hadError) 1485 return ExprError(); 1486 1487 SmallVector<SourceLocation, 4> StringTokLocs; 1488 for (unsigned i = 0; i != NumStringToks; ++i) 1489 StringTokLocs.push_back(StringToks[i].getLocation()); 1490 1491 QualType CharTy = Context.CharTy; 1492 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1493 if (Literal.isWide()) { 1494 CharTy = Context.getWideCharType(); 1495 Kind = StringLiteral::Wide; 1496 } else if (Literal.isUTF8()) { 1497 Kind = StringLiteral::UTF8; 1498 } else if (Literal.isUTF16()) { 1499 CharTy = Context.Char16Ty; 1500 Kind = StringLiteral::UTF16; 1501 } else if (Literal.isUTF32()) { 1502 CharTy = Context.Char32Ty; 1503 Kind = StringLiteral::UTF32; 1504 } else if (Literal.isPascal()) { 1505 CharTy = Context.UnsignedCharTy; 1506 } 1507 1508 QualType CharTyConst = CharTy; 1509 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1510 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1511 CharTyConst.addConst(); 1512 1513 // Get an array type for the string, according to C99 6.4.5. This includes 1514 // the nul terminator character as well as the string length for pascal 1515 // strings. 1516 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1517 llvm::APInt(32, Literal.GetNumStringChars()+1), 1518 ArrayType::Normal, 0); 1519 1520 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1521 if (getLangOpts().OpenCL) { 1522 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1523 } 1524 1525 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1526 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1527 Kind, Literal.Pascal, StrTy, 1528 &StringTokLocs[0], 1529 StringTokLocs.size()); 1530 if (Literal.getUDSuffix().empty()) 1531 return Owned(Lit); 1532 1533 // We're building a user-defined literal. 1534 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1535 SourceLocation UDSuffixLoc = 1536 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1537 Literal.getUDSuffixOffset()); 1538 1539 // Make sure we're allowed user-defined literals here. 1540 if (!UDLScope) 1541 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1542 1543 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1544 // operator "" X (str, len) 1545 QualType SizeType = Context.getSizeType(); 1546 1547 DeclarationName OpName = 1548 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1549 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1550 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1551 1552 QualType ArgTy[] = { 1553 Context.getArrayDecayedType(StrTy), SizeType 1554 }; 1555 1556 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1557 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1558 /*AllowRaw*/false, /*AllowTemplate*/false, 1559 /*AllowStringTemplate*/true)) { 1560 1561 case LOLR_Cooked: { 1562 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1563 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1564 StringTokLocs[0]); 1565 Expr *Args[] = { Lit, LenArg }; 1566 1567 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1568 } 1569 1570 case LOLR_StringTemplate: { 1571 TemplateArgumentListInfo ExplicitArgs; 1572 1573 unsigned CharBits = Context.getIntWidth(CharTy); 1574 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1575 llvm::APSInt Value(CharBits, CharIsUnsigned); 1576 1577 TemplateArgument TypeArg(CharTy); 1578 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1579 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1580 1581 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1582 Value = Lit->getCodeUnit(I); 1583 TemplateArgument Arg(Context, Value, CharTy); 1584 TemplateArgumentLocInfo ArgInfo; 1585 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1586 } 1587 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1588 &ExplicitArgs); 1589 } 1590 case LOLR_Raw: 1591 case LOLR_Template: 1592 llvm_unreachable("unexpected literal operator lookup result"); 1593 case LOLR_Error: 1594 return ExprError(); 1595 } 1596 llvm_unreachable("unexpected literal operator lookup result"); 1597} 1598 1599ExprResult 1600Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1601 SourceLocation Loc, 1602 const CXXScopeSpec *SS) { 1603 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1604 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1605} 1606 1607/// BuildDeclRefExpr - Build an expression that references a 1608/// declaration that does not require a closure capture. 1609ExprResult 1610Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1611 const DeclarationNameInfo &NameInfo, 1612 const CXXScopeSpec *SS, NamedDecl *FoundD, 1613 const TemplateArgumentListInfo *TemplateArgs) { 1614 if (getLangOpts().CUDA) 1615 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1616 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1617 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1618 CalleeTarget = IdentifyCUDATarget(Callee); 1619 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1620 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1621 << CalleeTarget << D->getIdentifier() << CallerTarget; 1622 Diag(D->getLocation(), diag::note_previous_decl) 1623 << D->getIdentifier(); 1624 return ExprError(); 1625 } 1626 } 1627 1628 bool refersToEnclosingScope = 1629 (CurContext != D->getDeclContext() && 1630 D->getDeclContext()->isFunctionOrMethod()) || 1631 (isa<VarDecl>(D) && 1632 cast<VarDecl>(D)->isInitCapture()); 1633 1634 DeclRefExpr *E; 1635 if (isa<VarTemplateSpecializationDecl>(D)) { 1636 VarTemplateSpecializationDecl *VarSpec = 1637 cast<VarTemplateSpecializationDecl>(D); 1638 1639 E = DeclRefExpr::Create( 1640 Context, 1641 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1642 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1643 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1644 } else { 1645 assert(!TemplateArgs && "No template arguments for non-variable" 1646 " template specialization referrences"); 1647 E = DeclRefExpr::Create( 1648 Context, 1649 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1650 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1651 } 1652 1653 MarkDeclRefReferenced(E); 1654 1655 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1656 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1657 DiagnosticsEngine::Level Level = 1658 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1659 E->getLocStart()); 1660 if (Level != DiagnosticsEngine::Ignored) 1661 recordUseOfEvaluatedWeak(E); 1662 } 1663 1664 // Just in case we're building an illegal pointer-to-member. 1665 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1666 if (FD && FD->isBitField()) 1667 E->setObjectKind(OK_BitField); 1668 1669 return Owned(E); 1670} 1671 1672/// Decomposes the given name into a DeclarationNameInfo, its location, and 1673/// possibly a list of template arguments. 1674/// 1675/// If this produces template arguments, it is permitted to call 1676/// DecomposeTemplateName. 1677/// 1678/// This actually loses a lot of source location information for 1679/// non-standard name kinds; we should consider preserving that in 1680/// some way. 1681void 1682Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1683 TemplateArgumentListInfo &Buffer, 1684 DeclarationNameInfo &NameInfo, 1685 const TemplateArgumentListInfo *&TemplateArgs) { 1686 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1687 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1688 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1689 1690 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1691 Id.TemplateId->NumArgs); 1692 translateTemplateArguments(TemplateArgsPtr, Buffer); 1693 1694 TemplateName TName = Id.TemplateId->Template.get(); 1695 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1696 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1697 TemplateArgs = &Buffer; 1698 } else { 1699 NameInfo = GetNameFromUnqualifiedId(Id); 1700 TemplateArgs = 0; 1701 } 1702} 1703 1704/// Diagnose an empty lookup. 1705/// 1706/// \return false if new lookup candidates were found 1707bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1708 CorrectionCandidateCallback &CCC, 1709 TemplateArgumentListInfo *ExplicitTemplateArgs, 1710 ArrayRef<Expr *> Args) { 1711 DeclarationName Name = R.getLookupName(); 1712 1713 unsigned diagnostic = diag::err_undeclared_var_use; 1714 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1715 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1716 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1717 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1718 diagnostic = diag::err_undeclared_use; 1719 diagnostic_suggest = diag::err_undeclared_use_suggest; 1720 } 1721 1722 // If the original lookup was an unqualified lookup, fake an 1723 // unqualified lookup. This is useful when (for example) the 1724 // original lookup would not have found something because it was a 1725 // dependent name. 1726 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1727 ? CurContext : 0; 1728 while (DC) { 1729 if (isa<CXXRecordDecl>(DC)) { 1730 LookupQualifiedName(R, DC); 1731 1732 if (!R.empty()) { 1733 // Don't give errors about ambiguities in this lookup. 1734 R.suppressDiagnostics(); 1735 1736 // During a default argument instantiation the CurContext points 1737 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1738 // function parameter list, hence add an explicit check. 1739 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1740 ActiveTemplateInstantiations.back().Kind == 1741 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1742 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1743 bool isInstance = CurMethod && 1744 CurMethod->isInstance() && 1745 DC == CurMethod->getParent() && !isDefaultArgument; 1746 1747 1748 // Give a code modification hint to insert 'this->'. 1749 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1750 // Actually quite difficult! 1751 if (getLangOpts().MicrosoftMode) 1752 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1753 if (isInstance) { 1754 Diag(R.getNameLoc(), diagnostic) << Name 1755 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1756 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1757 CallsUndergoingInstantiation.back()->getCallee()); 1758 1759 CXXMethodDecl *DepMethod; 1760 if (CurMethod->isDependentContext()) 1761 DepMethod = CurMethod; 1762 else if (CurMethod->getTemplatedKind() == 1763 FunctionDecl::TK_FunctionTemplateSpecialization) 1764 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1765 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1766 else 1767 DepMethod = cast<CXXMethodDecl>( 1768 CurMethod->getInstantiatedFromMemberFunction()); 1769 assert(DepMethod && "No template pattern found"); 1770 1771 QualType DepThisType = DepMethod->getThisType(Context); 1772 CheckCXXThisCapture(R.getNameLoc()); 1773 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1774 R.getNameLoc(), DepThisType, false); 1775 TemplateArgumentListInfo TList; 1776 if (ULE->hasExplicitTemplateArgs()) 1777 ULE->copyTemplateArgumentsInto(TList); 1778 1779 CXXScopeSpec SS; 1780 SS.Adopt(ULE->getQualifierLoc()); 1781 CXXDependentScopeMemberExpr *DepExpr = 1782 CXXDependentScopeMemberExpr::Create( 1783 Context, DepThis, DepThisType, true, SourceLocation(), 1784 SS.getWithLocInContext(Context), 1785 ULE->getTemplateKeywordLoc(), 0, 1786 R.getLookupNameInfo(), 1787 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1788 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1789 } else { 1790 Diag(R.getNameLoc(), diagnostic) << Name; 1791 } 1792 1793 // Do we really want to note all of these? 1794 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1795 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1796 1797 // Return true if we are inside a default argument instantiation 1798 // and the found name refers to an instance member function, otherwise 1799 // the function calling DiagnoseEmptyLookup will try to create an 1800 // implicit member call and this is wrong for default argument. 1801 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1802 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1803 return true; 1804 } 1805 1806 // Tell the callee to try to recover. 1807 return false; 1808 } 1809 1810 R.clear(); 1811 } 1812 1813 // In Microsoft mode, if we are performing lookup from within a friend 1814 // function definition declared at class scope then we must set 1815 // DC to the lexical parent to be able to search into the parent 1816 // class. 1817 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1818 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1819 DC->getLexicalParent()->isRecord()) 1820 DC = DC->getLexicalParent(); 1821 else 1822 DC = DC->getParent(); 1823 } 1824 1825 // We didn't find anything, so try to correct for a typo. 1826 TypoCorrection Corrected; 1827 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1828 S, &SS, CCC))) { 1829 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1830 bool DroppedSpecifier = 1831 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1832 R.setLookupName(Corrected.getCorrection()); 1833 1834 bool AcceptableWithRecovery = false; 1835 bool AcceptableWithoutRecovery = false; 1836 NamedDecl *ND = Corrected.getCorrectionDecl(); 1837 if (ND) { 1838 if (Corrected.isOverloaded()) { 1839 OverloadCandidateSet OCS(R.getNameLoc()); 1840 OverloadCandidateSet::iterator Best; 1841 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1842 CDEnd = Corrected.end(); 1843 CD != CDEnd; ++CD) { 1844 if (FunctionTemplateDecl *FTD = 1845 dyn_cast<FunctionTemplateDecl>(*CD)) 1846 AddTemplateOverloadCandidate( 1847 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1848 Args, OCS); 1849 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1850 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1851 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1852 Args, OCS); 1853 } 1854 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1855 case OR_Success: 1856 ND = Best->Function; 1857 Corrected.setCorrectionDecl(ND); 1858 break; 1859 default: 1860 // FIXME: Arbitrarily pick the first declaration for the note. 1861 Corrected.setCorrectionDecl(ND); 1862 break; 1863 } 1864 } 1865 R.addDecl(ND); 1866 1867 AcceptableWithRecovery = 1868 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1869 // FIXME: If we ended up with a typo for a type name or 1870 // Objective-C class name, we're in trouble because the parser 1871 // is in the wrong place to recover. Suggest the typo 1872 // correction, but don't make it a fix-it since we're not going 1873 // to recover well anyway. 1874 AcceptableWithoutRecovery = 1875 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1876 } else { 1877 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1878 // because we aren't able to recover. 1879 AcceptableWithoutRecovery = true; 1880 } 1881 1882 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1883 unsigned NoteID = (Corrected.getCorrectionDecl() && 1884 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1885 ? diag::note_implicit_param_decl 1886 : diag::note_previous_decl; 1887 if (SS.isEmpty()) 1888 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1889 PDiag(NoteID), AcceptableWithRecovery); 1890 else 1891 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1892 << Name << computeDeclContext(SS, false) 1893 << DroppedSpecifier << SS.getRange(), 1894 PDiag(NoteID), AcceptableWithRecovery); 1895 1896 // Tell the callee whether to try to recover. 1897 return !AcceptableWithRecovery; 1898 } 1899 } 1900 R.clear(); 1901 1902 // Emit a special diagnostic for failed member lookups. 1903 // FIXME: computing the declaration context might fail here (?) 1904 if (!SS.isEmpty()) { 1905 Diag(R.getNameLoc(), diag::err_no_member) 1906 << Name << computeDeclContext(SS, false) 1907 << SS.getRange(); 1908 return true; 1909 } 1910 1911 // Give up, we can't recover. 1912 Diag(R.getNameLoc(), diagnostic) << Name; 1913 return true; 1914} 1915 1916ExprResult Sema::ActOnIdExpression(Scope *S, 1917 CXXScopeSpec &SS, 1918 SourceLocation TemplateKWLoc, 1919 UnqualifiedId &Id, 1920 bool HasTrailingLParen, 1921 bool IsAddressOfOperand, 1922 CorrectionCandidateCallback *CCC, 1923 bool IsInlineAsmIdentifier) { 1924 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1925 "cannot be direct & operand and have a trailing lparen"); 1926 if (SS.isInvalid()) 1927 return ExprError(); 1928 1929 TemplateArgumentListInfo TemplateArgsBuffer; 1930 1931 // Decompose the UnqualifiedId into the following data. 1932 DeclarationNameInfo NameInfo; 1933 const TemplateArgumentListInfo *TemplateArgs; 1934 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1935 1936 DeclarationName Name = NameInfo.getName(); 1937 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1938 SourceLocation NameLoc = NameInfo.getLoc(); 1939 1940 // C++ [temp.dep.expr]p3: 1941 // An id-expression is type-dependent if it contains: 1942 // -- an identifier that was declared with a dependent type, 1943 // (note: handled after lookup) 1944 // -- a template-id that is dependent, 1945 // (note: handled in BuildTemplateIdExpr) 1946 // -- a conversion-function-id that specifies a dependent type, 1947 // -- a nested-name-specifier that contains a class-name that 1948 // names a dependent type. 1949 // Determine whether this is a member of an unknown specialization; 1950 // we need to handle these differently. 1951 bool DependentID = false; 1952 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1953 Name.getCXXNameType()->isDependentType()) { 1954 DependentID = true; 1955 } else if (SS.isSet()) { 1956 if (DeclContext *DC = computeDeclContext(SS, false)) { 1957 if (RequireCompleteDeclContext(SS, DC)) 1958 return ExprError(); 1959 } else { 1960 DependentID = true; 1961 } 1962 } 1963 1964 if (DependentID) 1965 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1966 IsAddressOfOperand, TemplateArgs); 1967 1968 // Perform the required lookup. 1969 LookupResult R(*this, NameInfo, 1970 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1971 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1972 if (TemplateArgs) { 1973 // Lookup the template name again to correctly establish the context in 1974 // which it was found. This is really unfortunate as we already did the 1975 // lookup to determine that it was a template name in the first place. If 1976 // this becomes a performance hit, we can work harder to preserve those 1977 // results until we get here but it's likely not worth it. 1978 bool MemberOfUnknownSpecialization; 1979 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1980 MemberOfUnknownSpecialization); 1981 1982 if (MemberOfUnknownSpecialization || 1983 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1984 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1985 IsAddressOfOperand, TemplateArgs); 1986 } else { 1987 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1988 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1989 1990 // If the result might be in a dependent base class, this is a dependent 1991 // id-expression. 1992 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1993 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1994 IsAddressOfOperand, TemplateArgs); 1995 1996 // If this reference is in an Objective-C method, then we need to do 1997 // some special Objective-C lookup, too. 1998 if (IvarLookupFollowUp) { 1999 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2000 if (E.isInvalid()) 2001 return ExprError(); 2002 2003 if (Expr *Ex = E.takeAs<Expr>()) 2004 return Owned(Ex); 2005 } 2006 } 2007 2008 if (R.isAmbiguous()) 2009 return ExprError(); 2010 2011 // Determine whether this name might be a candidate for 2012 // argument-dependent lookup. 2013 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2014 2015 if (R.empty() && !ADL) { 2016 2017 // Otherwise, this could be an implicitly declared function reference (legal 2018 // in C90, extension in C99, forbidden in C++). 2019 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2020 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2021 if (D) R.addDecl(D); 2022 } 2023 2024 // If this name wasn't predeclared and if this is not a function 2025 // call, diagnose the problem. 2026 if (R.empty()) { 2027 // In Microsoft mode, if we are inside a template class member function 2028 // whose parent class has dependent base classes, and we can't resolve 2029 // an identifier, then assume the identifier is a member of a dependent 2030 // base class. The goal is to postpone name lookup to instantiation time 2031 // to be able to search into the type dependent base classes. 2032 // FIXME: If we want 100% compatibility with MSVC, we will have delay all 2033 // unqualified name lookup. Any name lookup during template parsing means 2034 // clang might find something that MSVC doesn't. For now, we only handle 2035 // the common case of members of a dependent base class. 2036 if (getLangOpts().MicrosoftMode) { 2037 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2038 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2039 assert(SS.isEmpty() && "qualifiers should be already handled"); 2040 QualType ThisType = MD->getThisType(Context); 2041 // Since the 'this' expression is synthesized, we don't need to 2042 // perform the double-lookup check. 2043 NamedDecl *FirstQualifierInScope = 0; 2044 return Owned(CXXDependentScopeMemberExpr::Create( 2045 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2046 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2047 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2048 } 2049 } 2050 2051 // Don't diagnose an empty lookup for inline assmebly. 2052 if (IsInlineAsmIdentifier) 2053 return ExprError(); 2054 2055 CorrectionCandidateCallback DefaultValidator; 2056 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2057 return ExprError(); 2058 2059 assert(!R.empty() && 2060 "DiagnoseEmptyLookup returned false but added no results"); 2061 2062 // If we found an Objective-C instance variable, let 2063 // LookupInObjCMethod build the appropriate expression to 2064 // reference the ivar. 2065 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2066 R.clear(); 2067 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2068 // In a hopelessly buggy code, Objective-C instance variable 2069 // lookup fails and no expression will be built to reference it. 2070 if (!E.isInvalid() && !E.get()) 2071 return ExprError(); 2072 return E; 2073 } 2074 } 2075 } 2076 2077 // This is guaranteed from this point on. 2078 assert(!R.empty() || ADL); 2079 2080 // Check whether this might be a C++ implicit instance member access. 2081 // C++ [class.mfct.non-static]p3: 2082 // When an id-expression that is not part of a class member access 2083 // syntax and not used to form a pointer to member is used in the 2084 // body of a non-static member function of class X, if name lookup 2085 // resolves the name in the id-expression to a non-static non-type 2086 // member of some class C, the id-expression is transformed into a 2087 // class member access expression using (*this) as the 2088 // postfix-expression to the left of the . operator. 2089 // 2090 // But we don't actually need to do this for '&' operands if R 2091 // resolved to a function or overloaded function set, because the 2092 // expression is ill-formed if it actually works out to be a 2093 // non-static member function: 2094 // 2095 // C++ [expr.ref]p4: 2096 // Otherwise, if E1.E2 refers to a non-static member function. . . 2097 // [t]he expression can be used only as the left-hand operand of a 2098 // member function call. 2099 // 2100 // There are other safeguards against such uses, but it's important 2101 // to get this right here so that we don't end up making a 2102 // spuriously dependent expression if we're inside a dependent 2103 // instance method. 2104 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2105 bool MightBeImplicitMember; 2106 if (!IsAddressOfOperand) 2107 MightBeImplicitMember = true; 2108 else if (!SS.isEmpty()) 2109 MightBeImplicitMember = false; 2110 else if (R.isOverloadedResult()) 2111 MightBeImplicitMember = false; 2112 else if (R.isUnresolvableResult()) 2113 MightBeImplicitMember = true; 2114 else 2115 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2116 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2117 isa<MSPropertyDecl>(R.getFoundDecl()); 2118 2119 if (MightBeImplicitMember) 2120 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2121 R, TemplateArgs); 2122 } 2123 2124 if (TemplateArgs || TemplateKWLoc.isValid()) { 2125 2126 // In C++1y, if this is a variable template id, then check it 2127 // in BuildTemplateIdExpr(). 2128 // The single lookup result must be a variable template declaration. 2129 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2130 Id.TemplateId->Kind == TNK_Var_template) { 2131 assert(R.getAsSingle<VarTemplateDecl>() && 2132 "There should only be one declaration found."); 2133 } 2134 2135 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2136 } 2137 2138 return BuildDeclarationNameExpr(SS, R, ADL); 2139} 2140 2141/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2142/// declaration name, generally during template instantiation. 2143/// There's a large number of things which don't need to be done along 2144/// this path. 2145ExprResult 2146Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2147 const DeclarationNameInfo &NameInfo, 2148 bool IsAddressOfOperand) { 2149 DeclContext *DC = computeDeclContext(SS, false); 2150 if (!DC) 2151 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2152 NameInfo, /*TemplateArgs=*/0); 2153 2154 if (RequireCompleteDeclContext(SS, DC)) 2155 return ExprError(); 2156 2157 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2158 LookupQualifiedName(R, DC); 2159 2160 if (R.isAmbiguous()) 2161 return ExprError(); 2162 2163 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2164 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2165 NameInfo, /*TemplateArgs=*/0); 2166 2167 if (R.empty()) { 2168 Diag(NameInfo.getLoc(), diag::err_no_member) 2169 << NameInfo.getName() << DC << SS.getRange(); 2170 return ExprError(); 2171 } 2172 2173 // Defend against this resolving to an implicit member access. We usually 2174 // won't get here if this might be a legitimate a class member (we end up in 2175 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2176 // a pointer-to-member or in an unevaluated context in C++11. 2177 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2178 return BuildPossibleImplicitMemberExpr(SS, 2179 /*TemplateKWLoc=*/SourceLocation(), 2180 R, /*TemplateArgs=*/0); 2181 2182 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2183} 2184 2185/// LookupInObjCMethod - The parser has read a name in, and Sema has 2186/// detected that we're currently inside an ObjC method. Perform some 2187/// additional lookup. 2188/// 2189/// Ideally, most of this would be done by lookup, but there's 2190/// actually quite a lot of extra work involved. 2191/// 2192/// Returns a null sentinel to indicate trivial success. 2193ExprResult 2194Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2195 IdentifierInfo *II, bool AllowBuiltinCreation) { 2196 SourceLocation Loc = Lookup.getNameLoc(); 2197 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2198 2199 // Check for error condition which is already reported. 2200 if (!CurMethod) 2201 return ExprError(); 2202 2203 // There are two cases to handle here. 1) scoped lookup could have failed, 2204 // in which case we should look for an ivar. 2) scoped lookup could have 2205 // found a decl, but that decl is outside the current instance method (i.e. 2206 // a global variable). In these two cases, we do a lookup for an ivar with 2207 // this name, if the lookup sucedes, we replace it our current decl. 2208 2209 // If we're in a class method, we don't normally want to look for 2210 // ivars. But if we don't find anything else, and there's an 2211 // ivar, that's an error. 2212 bool IsClassMethod = CurMethod->isClassMethod(); 2213 2214 bool LookForIvars; 2215 if (Lookup.empty()) 2216 LookForIvars = true; 2217 else if (IsClassMethod) 2218 LookForIvars = false; 2219 else 2220 LookForIvars = (Lookup.isSingleResult() && 2221 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2222 ObjCInterfaceDecl *IFace = 0; 2223 if (LookForIvars) { 2224 IFace = CurMethod->getClassInterface(); 2225 ObjCInterfaceDecl *ClassDeclared; 2226 ObjCIvarDecl *IV = 0; 2227 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2228 // Diagnose using an ivar in a class method. 2229 if (IsClassMethod) 2230 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2231 << IV->getDeclName()); 2232 2233 // If we're referencing an invalid decl, just return this as a silent 2234 // error node. The error diagnostic was already emitted on the decl. 2235 if (IV->isInvalidDecl()) 2236 return ExprError(); 2237 2238 // Check if referencing a field with __attribute__((deprecated)). 2239 if (DiagnoseUseOfDecl(IV, Loc)) 2240 return ExprError(); 2241 2242 // Diagnose the use of an ivar outside of the declaring class. 2243 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2244 !declaresSameEntity(ClassDeclared, IFace) && 2245 !getLangOpts().DebuggerSupport) 2246 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2247 2248 // FIXME: This should use a new expr for a direct reference, don't 2249 // turn this into Self->ivar, just return a BareIVarExpr or something. 2250 IdentifierInfo &II = Context.Idents.get("self"); 2251 UnqualifiedId SelfName; 2252 SelfName.setIdentifier(&II, SourceLocation()); 2253 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2254 CXXScopeSpec SelfScopeSpec; 2255 SourceLocation TemplateKWLoc; 2256 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2257 SelfName, false, false); 2258 if (SelfExpr.isInvalid()) 2259 return ExprError(); 2260 2261 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2262 if (SelfExpr.isInvalid()) 2263 return ExprError(); 2264 2265 MarkAnyDeclReferenced(Loc, IV, true); 2266 if (!IV->getBackingIvarReferencedInAccessor()) { 2267 // Mark this ivar 'referenced' in this method, if it is a backing ivar 2268 // of a property and current method is one of its property accessor. 2269 const ObjCPropertyDecl *PDecl; 2270 const ObjCIvarDecl *BIV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 2271 if (BIV && BIV == IV) 2272 IV->setBackingIvarReferencedInAccessor(true); 2273 } 2274 2275 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2276 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2277 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2278 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2279 2280 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2281 Loc, IV->getLocation(), 2282 SelfExpr.take(), 2283 true, true); 2284 2285 if (getLangOpts().ObjCAutoRefCount) { 2286 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2287 DiagnosticsEngine::Level Level = 2288 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2289 if (Level != DiagnosticsEngine::Ignored) 2290 recordUseOfEvaluatedWeak(Result); 2291 } 2292 if (CurContext->isClosure()) 2293 Diag(Loc, diag::warn_implicitly_retains_self) 2294 << FixItHint::CreateInsertion(Loc, "self->"); 2295 } 2296 2297 return Owned(Result); 2298 } 2299 } else if (CurMethod->isInstanceMethod()) { 2300 // We should warn if a local variable hides an ivar. 2301 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2302 ObjCInterfaceDecl *ClassDeclared; 2303 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2304 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2305 declaresSameEntity(IFace, ClassDeclared)) 2306 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2307 } 2308 } 2309 } else if (Lookup.isSingleResult() && 2310 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2311 // If accessing a stand-alone ivar in a class method, this is an error. 2312 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2313 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2314 << IV->getDeclName()); 2315 } 2316 2317 if (Lookup.empty() && II && AllowBuiltinCreation) { 2318 // FIXME. Consolidate this with similar code in LookupName. 2319 if (unsigned BuiltinID = II->getBuiltinID()) { 2320 if (!(getLangOpts().CPlusPlus && 2321 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2322 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2323 S, Lookup.isForRedeclaration(), 2324 Lookup.getNameLoc()); 2325 if (D) Lookup.addDecl(D); 2326 } 2327 } 2328 } 2329 // Sentinel value saying that we didn't do anything special. 2330 return Owned((Expr*) 0); 2331} 2332 2333/// \brief Cast a base object to a member's actual type. 2334/// 2335/// Logically this happens in three phases: 2336/// 2337/// * First we cast from the base type to the naming class. 2338/// The naming class is the class into which we were looking 2339/// when we found the member; it's the qualifier type if a 2340/// qualifier was provided, and otherwise it's the base type. 2341/// 2342/// * Next we cast from the naming class to the declaring class. 2343/// If the member we found was brought into a class's scope by 2344/// a using declaration, this is that class; otherwise it's 2345/// the class declaring the member. 2346/// 2347/// * Finally we cast from the declaring class to the "true" 2348/// declaring class of the member. This conversion does not 2349/// obey access control. 2350ExprResult 2351Sema::PerformObjectMemberConversion(Expr *From, 2352 NestedNameSpecifier *Qualifier, 2353 NamedDecl *FoundDecl, 2354 NamedDecl *Member) { 2355 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2356 if (!RD) 2357 return Owned(From); 2358 2359 QualType DestRecordType; 2360 QualType DestType; 2361 QualType FromRecordType; 2362 QualType FromType = From->getType(); 2363 bool PointerConversions = false; 2364 if (isa<FieldDecl>(Member)) { 2365 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2366 2367 if (FromType->getAs<PointerType>()) { 2368 DestType = Context.getPointerType(DestRecordType); 2369 FromRecordType = FromType->getPointeeType(); 2370 PointerConversions = true; 2371 } else { 2372 DestType = DestRecordType; 2373 FromRecordType = FromType; 2374 } 2375 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2376 if (Method->isStatic()) 2377 return Owned(From); 2378 2379 DestType = Method->getThisType(Context); 2380 DestRecordType = DestType->getPointeeType(); 2381 2382 if (FromType->getAs<PointerType>()) { 2383 FromRecordType = FromType->getPointeeType(); 2384 PointerConversions = true; 2385 } else { 2386 FromRecordType = FromType; 2387 DestType = DestRecordType; 2388 } 2389 } else { 2390 // No conversion necessary. 2391 return Owned(From); 2392 } 2393 2394 if (DestType->isDependentType() || FromType->isDependentType()) 2395 return Owned(From); 2396 2397 // If the unqualified types are the same, no conversion is necessary. 2398 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2399 return Owned(From); 2400 2401 SourceRange FromRange = From->getSourceRange(); 2402 SourceLocation FromLoc = FromRange.getBegin(); 2403 2404 ExprValueKind VK = From->getValueKind(); 2405 2406 // C++ [class.member.lookup]p8: 2407 // [...] Ambiguities can often be resolved by qualifying a name with its 2408 // class name. 2409 // 2410 // If the member was a qualified name and the qualified referred to a 2411 // specific base subobject type, we'll cast to that intermediate type 2412 // first and then to the object in which the member is declared. That allows 2413 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2414 // 2415 // class Base { public: int x; }; 2416 // class Derived1 : public Base { }; 2417 // class Derived2 : public Base { }; 2418 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2419 // 2420 // void VeryDerived::f() { 2421 // x = 17; // error: ambiguous base subobjects 2422 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2423 // } 2424 if (Qualifier && Qualifier->getAsType()) { 2425 QualType QType = QualType(Qualifier->getAsType(), 0); 2426 assert(QType->isRecordType() && "lookup done with non-record type"); 2427 2428 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2429 2430 // In C++98, the qualifier type doesn't actually have to be a base 2431 // type of the object type, in which case we just ignore it. 2432 // Otherwise build the appropriate casts. 2433 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2434 CXXCastPath BasePath; 2435 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2436 FromLoc, FromRange, &BasePath)) 2437 return ExprError(); 2438 2439 if (PointerConversions) 2440 QType = Context.getPointerType(QType); 2441 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2442 VK, &BasePath).take(); 2443 2444 FromType = QType; 2445 FromRecordType = QRecordType; 2446 2447 // If the qualifier type was the same as the destination type, 2448 // we're done. 2449 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2450 return Owned(From); 2451 } 2452 } 2453 2454 bool IgnoreAccess = false; 2455 2456 // If we actually found the member through a using declaration, cast 2457 // down to the using declaration's type. 2458 // 2459 // Pointer equality is fine here because only one declaration of a 2460 // class ever has member declarations. 2461 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2462 assert(isa<UsingShadowDecl>(FoundDecl)); 2463 QualType URecordType = Context.getTypeDeclType( 2464 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2465 2466 // We only need to do this if the naming-class to declaring-class 2467 // conversion is non-trivial. 2468 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2469 assert(IsDerivedFrom(FromRecordType, URecordType)); 2470 CXXCastPath BasePath; 2471 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2472 FromLoc, FromRange, &BasePath)) 2473 return ExprError(); 2474 2475 QualType UType = URecordType; 2476 if (PointerConversions) 2477 UType = Context.getPointerType(UType); 2478 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2479 VK, &BasePath).take(); 2480 FromType = UType; 2481 FromRecordType = URecordType; 2482 } 2483 2484 // We don't do access control for the conversion from the 2485 // declaring class to the true declaring class. 2486 IgnoreAccess = true; 2487 } 2488 2489 CXXCastPath BasePath; 2490 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2491 FromLoc, FromRange, &BasePath, 2492 IgnoreAccess)) 2493 return ExprError(); 2494 2495 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2496 VK, &BasePath); 2497} 2498 2499bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2500 const LookupResult &R, 2501 bool HasTrailingLParen) { 2502 // Only when used directly as the postfix-expression of a call. 2503 if (!HasTrailingLParen) 2504 return false; 2505 2506 // Never if a scope specifier was provided. 2507 if (SS.isSet()) 2508 return false; 2509 2510 // Only in C++ or ObjC++. 2511 if (!getLangOpts().CPlusPlus) 2512 return false; 2513 2514 // Turn off ADL when we find certain kinds of declarations during 2515 // normal lookup: 2516 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2517 NamedDecl *D = *I; 2518 2519 // C++0x [basic.lookup.argdep]p3: 2520 // -- a declaration of a class member 2521 // Since using decls preserve this property, we check this on the 2522 // original decl. 2523 if (D->isCXXClassMember()) 2524 return false; 2525 2526 // C++0x [basic.lookup.argdep]p3: 2527 // -- a block-scope function declaration that is not a 2528 // using-declaration 2529 // NOTE: we also trigger this for function templates (in fact, we 2530 // don't check the decl type at all, since all other decl types 2531 // turn off ADL anyway). 2532 if (isa<UsingShadowDecl>(D)) 2533 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2534 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2535 return false; 2536 2537 // C++0x [basic.lookup.argdep]p3: 2538 // -- a declaration that is neither a function or a function 2539 // template 2540 // And also for builtin functions. 2541 if (isa<FunctionDecl>(D)) { 2542 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2543 2544 // But also builtin functions. 2545 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2546 return false; 2547 } else if (!isa<FunctionTemplateDecl>(D)) 2548 return false; 2549 } 2550 2551 return true; 2552} 2553 2554 2555/// Diagnoses obvious problems with the use of the given declaration 2556/// as an expression. This is only actually called for lookups that 2557/// were not overloaded, and it doesn't promise that the declaration 2558/// will in fact be used. 2559static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2560 if (isa<TypedefNameDecl>(D)) { 2561 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2562 return true; 2563 } 2564 2565 if (isa<ObjCInterfaceDecl>(D)) { 2566 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2567 return true; 2568 } 2569 2570 if (isa<NamespaceDecl>(D)) { 2571 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2572 return true; 2573 } 2574 2575 return false; 2576} 2577 2578ExprResult 2579Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2580 LookupResult &R, 2581 bool NeedsADL) { 2582 // If this is a single, fully-resolved result and we don't need ADL, 2583 // just build an ordinary singleton decl ref. 2584 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2585 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2586 R.getRepresentativeDecl()); 2587 2588 // We only need to check the declaration if there's exactly one 2589 // result, because in the overloaded case the results can only be 2590 // functions and function templates. 2591 if (R.isSingleResult() && 2592 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2593 return ExprError(); 2594 2595 // Otherwise, just build an unresolved lookup expression. Suppress 2596 // any lookup-related diagnostics; we'll hash these out later, when 2597 // we've picked a target. 2598 R.suppressDiagnostics(); 2599 2600 UnresolvedLookupExpr *ULE 2601 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2602 SS.getWithLocInContext(Context), 2603 R.getLookupNameInfo(), 2604 NeedsADL, R.isOverloadedResult(), 2605 R.begin(), R.end()); 2606 2607 return Owned(ULE); 2608} 2609 2610/// \brief Complete semantic analysis for a reference to the given declaration. 2611ExprResult Sema::BuildDeclarationNameExpr( 2612 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2613 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2614 assert(D && "Cannot refer to a NULL declaration"); 2615 assert(!isa<FunctionTemplateDecl>(D) && 2616 "Cannot refer unambiguously to a function template"); 2617 2618 SourceLocation Loc = NameInfo.getLoc(); 2619 if (CheckDeclInExpr(*this, Loc, D)) 2620 return ExprError(); 2621 2622 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2623 // Specifically diagnose references to class templates that are missing 2624 // a template argument list. 2625 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2626 << Template << SS.getRange(); 2627 Diag(Template->getLocation(), diag::note_template_decl_here); 2628 return ExprError(); 2629 } 2630 2631 // Make sure that we're referring to a value. 2632 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2633 if (!VD) { 2634 Diag(Loc, diag::err_ref_non_value) 2635 << D << SS.getRange(); 2636 Diag(D->getLocation(), diag::note_declared_at); 2637 return ExprError(); 2638 } 2639 2640 // Check whether this declaration can be used. Note that we suppress 2641 // this check when we're going to perform argument-dependent lookup 2642 // on this function name, because this might not be the function 2643 // that overload resolution actually selects. 2644 if (DiagnoseUseOfDecl(VD, Loc)) 2645 return ExprError(); 2646 2647 // Only create DeclRefExpr's for valid Decl's. 2648 if (VD->isInvalidDecl()) 2649 return ExprError(); 2650 2651 // Handle members of anonymous structs and unions. If we got here, 2652 // and the reference is to a class member indirect field, then this 2653 // must be the subject of a pointer-to-member expression. 2654 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2655 if (!indirectField->isCXXClassMember()) 2656 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2657 indirectField); 2658 2659 { 2660 QualType type = VD->getType(); 2661 ExprValueKind valueKind = VK_RValue; 2662 2663 switch (D->getKind()) { 2664 // Ignore all the non-ValueDecl kinds. 2665#define ABSTRACT_DECL(kind) 2666#define VALUE(type, base) 2667#define DECL(type, base) \ 2668 case Decl::type: 2669#include "clang/AST/DeclNodes.inc" 2670 llvm_unreachable("invalid value decl kind"); 2671 2672 // These shouldn't make it here. 2673 case Decl::ObjCAtDefsField: 2674 case Decl::ObjCIvar: 2675 llvm_unreachable("forming non-member reference to ivar?"); 2676 2677 // Enum constants are always r-values and never references. 2678 // Unresolved using declarations are dependent. 2679 case Decl::EnumConstant: 2680 case Decl::UnresolvedUsingValue: 2681 valueKind = VK_RValue; 2682 break; 2683 2684 // Fields and indirect fields that got here must be for 2685 // pointer-to-member expressions; we just call them l-values for 2686 // internal consistency, because this subexpression doesn't really 2687 // exist in the high-level semantics. 2688 case Decl::Field: 2689 case Decl::IndirectField: 2690 assert(getLangOpts().CPlusPlus && 2691 "building reference to field in C?"); 2692 2693 // These can't have reference type in well-formed programs, but 2694 // for internal consistency we do this anyway. 2695 type = type.getNonReferenceType(); 2696 valueKind = VK_LValue; 2697 break; 2698 2699 // Non-type template parameters are either l-values or r-values 2700 // depending on the type. 2701 case Decl::NonTypeTemplateParm: { 2702 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2703 type = reftype->getPointeeType(); 2704 valueKind = VK_LValue; // even if the parameter is an r-value reference 2705 break; 2706 } 2707 2708 // For non-references, we need to strip qualifiers just in case 2709 // the template parameter was declared as 'const int' or whatever. 2710 valueKind = VK_RValue; 2711 type = type.getUnqualifiedType(); 2712 break; 2713 } 2714 2715 case Decl::Var: 2716 case Decl::VarTemplateSpecialization: 2717 case Decl::VarTemplatePartialSpecialization: 2718 // In C, "extern void blah;" is valid and is an r-value. 2719 if (!getLangOpts().CPlusPlus && 2720 !type.hasQualifiers() && 2721 type->isVoidType()) { 2722 valueKind = VK_RValue; 2723 break; 2724 } 2725 // fallthrough 2726 2727 case Decl::ImplicitParam: 2728 case Decl::ParmVar: { 2729 // These are always l-values. 2730 valueKind = VK_LValue; 2731 type = type.getNonReferenceType(); 2732 2733 // FIXME: Does the addition of const really only apply in 2734 // potentially-evaluated contexts? Since the variable isn't actually 2735 // captured in an unevaluated context, it seems that the answer is no. 2736 if (!isUnevaluatedContext()) { 2737 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2738 if (!CapturedType.isNull()) 2739 type = CapturedType; 2740 } 2741 2742 break; 2743 } 2744 2745 case Decl::Function: { 2746 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2747 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2748 type = Context.BuiltinFnTy; 2749 valueKind = VK_RValue; 2750 break; 2751 } 2752 } 2753 2754 const FunctionType *fty = type->castAs<FunctionType>(); 2755 2756 // If we're referring to a function with an __unknown_anytype 2757 // result type, make the entire expression __unknown_anytype. 2758 if (fty->getResultType() == Context.UnknownAnyTy) { 2759 type = Context.UnknownAnyTy; 2760 valueKind = VK_RValue; 2761 break; 2762 } 2763 2764 // Functions are l-values in C++. 2765 if (getLangOpts().CPlusPlus) { 2766 valueKind = VK_LValue; 2767 break; 2768 } 2769 2770 // C99 DR 316 says that, if a function type comes from a 2771 // function definition (without a prototype), that type is only 2772 // used for checking compatibility. Therefore, when referencing 2773 // the function, we pretend that we don't have the full function 2774 // type. 2775 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2776 isa<FunctionProtoType>(fty)) 2777 type = Context.getFunctionNoProtoType(fty->getResultType(), 2778 fty->getExtInfo()); 2779 2780 // Functions are r-values in C. 2781 valueKind = VK_RValue; 2782 break; 2783 } 2784 2785 case Decl::MSProperty: 2786 valueKind = VK_LValue; 2787 break; 2788 2789 case Decl::CXXMethod: 2790 // If we're referring to a method with an __unknown_anytype 2791 // result type, make the entire expression __unknown_anytype. 2792 // This should only be possible with a type written directly. 2793 if (const FunctionProtoType *proto 2794 = dyn_cast<FunctionProtoType>(VD->getType())) 2795 if (proto->getResultType() == Context.UnknownAnyTy) { 2796 type = Context.UnknownAnyTy; 2797 valueKind = VK_RValue; 2798 break; 2799 } 2800 2801 // C++ methods are l-values if static, r-values if non-static. 2802 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2803 valueKind = VK_LValue; 2804 break; 2805 } 2806 // fallthrough 2807 2808 case Decl::CXXConversion: 2809 case Decl::CXXDestructor: 2810 case Decl::CXXConstructor: 2811 valueKind = VK_RValue; 2812 break; 2813 } 2814 2815 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2816 TemplateArgs); 2817 } 2818} 2819 2820ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2821 PredefinedExpr::IdentType IT) { 2822 // Pick the current block, lambda, captured statement or function. 2823 Decl *currentDecl = 0; 2824 if (const BlockScopeInfo *BSI = getCurBlock()) 2825 currentDecl = BSI->TheDecl; 2826 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2827 currentDecl = LSI->CallOperator; 2828 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2829 currentDecl = CSI->TheCapturedDecl; 2830 else 2831 currentDecl = getCurFunctionOrMethodDecl(); 2832 2833 if (!currentDecl) { 2834 Diag(Loc, diag::ext_predef_outside_function); 2835 currentDecl = Context.getTranslationUnitDecl(); 2836 } 2837 2838 QualType ResTy; 2839 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2840 ResTy = Context.DependentTy; 2841 else { 2842 // Pre-defined identifiers are of type char[x], where x is the length of 2843 // the string. 2844 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2845 2846 llvm::APInt LengthI(32, Length + 1); 2847 if (IT == PredefinedExpr::LFunction) 2848 ResTy = Context.WideCharTy.withConst(); 2849 else 2850 ResTy = Context.CharTy.withConst(); 2851 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2852 } 2853 2854 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2855} 2856 2857ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2858 PredefinedExpr::IdentType IT; 2859 2860 switch (Kind) { 2861 default: llvm_unreachable("Unknown simple primary expr!"); 2862 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2863 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2864 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2865 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2866 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2867 } 2868 2869 return BuildPredefinedExpr(Loc, IT); 2870} 2871 2872ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2873 SmallString<16> CharBuffer; 2874 bool Invalid = false; 2875 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2876 if (Invalid) 2877 return ExprError(); 2878 2879 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2880 PP, Tok.getKind()); 2881 if (Literal.hadError()) 2882 return ExprError(); 2883 2884 QualType Ty; 2885 if (Literal.isWide()) 2886 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2887 else if (Literal.isUTF16()) 2888 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2889 else if (Literal.isUTF32()) 2890 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2891 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2892 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2893 else 2894 Ty = Context.CharTy; // 'x' -> char in C++ 2895 2896 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2897 if (Literal.isWide()) 2898 Kind = CharacterLiteral::Wide; 2899 else if (Literal.isUTF16()) 2900 Kind = CharacterLiteral::UTF16; 2901 else if (Literal.isUTF32()) 2902 Kind = CharacterLiteral::UTF32; 2903 2904 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2905 Tok.getLocation()); 2906 2907 if (Literal.getUDSuffix().empty()) 2908 return Owned(Lit); 2909 2910 // We're building a user-defined literal. 2911 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2912 SourceLocation UDSuffixLoc = 2913 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2914 2915 // Make sure we're allowed user-defined literals here. 2916 if (!UDLScope) 2917 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2918 2919 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2920 // operator "" X (ch) 2921 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2922 Lit, Tok.getLocation()); 2923} 2924 2925ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2926 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2927 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2928 Context.IntTy, Loc)); 2929} 2930 2931static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2932 QualType Ty, SourceLocation Loc) { 2933 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2934 2935 using llvm::APFloat; 2936 APFloat Val(Format); 2937 2938 APFloat::opStatus result = Literal.GetFloatValue(Val); 2939 2940 // Overflow is always an error, but underflow is only an error if 2941 // we underflowed to zero (APFloat reports denormals as underflow). 2942 if ((result & APFloat::opOverflow) || 2943 ((result & APFloat::opUnderflow) && Val.isZero())) { 2944 unsigned diagnostic; 2945 SmallString<20> buffer; 2946 if (result & APFloat::opOverflow) { 2947 diagnostic = diag::warn_float_overflow; 2948 APFloat::getLargest(Format).toString(buffer); 2949 } else { 2950 diagnostic = diag::warn_float_underflow; 2951 APFloat::getSmallest(Format).toString(buffer); 2952 } 2953 2954 S.Diag(Loc, diagnostic) 2955 << Ty 2956 << StringRef(buffer.data(), buffer.size()); 2957 } 2958 2959 bool isExact = (result == APFloat::opOK); 2960 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2961} 2962 2963ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2964 // Fast path for a single digit (which is quite common). A single digit 2965 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2966 if (Tok.getLength() == 1) { 2967 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2968 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2969 } 2970 2971 SmallString<128> SpellingBuffer; 2972 // NumericLiteralParser wants to overread by one character. Add padding to 2973 // the buffer in case the token is copied to the buffer. If getSpelling() 2974 // returns a StringRef to the memory buffer, it should have a null char at 2975 // the EOF, so it is also safe. 2976 SpellingBuffer.resize(Tok.getLength() + 1); 2977 2978 // Get the spelling of the token, which eliminates trigraphs, etc. 2979 bool Invalid = false; 2980 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2981 if (Invalid) 2982 return ExprError(); 2983 2984 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2985 if (Literal.hadError) 2986 return ExprError(); 2987 2988 if (Literal.hasUDSuffix()) { 2989 // We're building a user-defined literal. 2990 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2991 SourceLocation UDSuffixLoc = 2992 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2993 2994 // Make sure we're allowed user-defined literals here. 2995 if (!UDLScope) 2996 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2997 2998 QualType CookedTy; 2999 if (Literal.isFloatingLiteral()) { 3000 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3001 // long double, the literal is treated as a call of the form 3002 // operator "" X (f L) 3003 CookedTy = Context.LongDoubleTy; 3004 } else { 3005 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3006 // unsigned long long, the literal is treated as a call of the form 3007 // operator "" X (n ULL) 3008 CookedTy = Context.UnsignedLongLongTy; 3009 } 3010 3011 DeclarationName OpName = 3012 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3013 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3014 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3015 3016 SourceLocation TokLoc = Tok.getLocation(); 3017 3018 // Perform literal operator lookup to determine if we're building a raw 3019 // literal or a cooked one. 3020 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3021 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3022 /*AllowRaw*/true, /*AllowTemplate*/true, 3023 /*AllowStringTemplate*/false)) { 3024 case LOLR_Error: 3025 return ExprError(); 3026 3027 case LOLR_Cooked: { 3028 Expr *Lit; 3029 if (Literal.isFloatingLiteral()) { 3030 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3031 } else { 3032 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3033 if (Literal.GetIntegerValue(ResultVal)) 3034 Diag(Tok.getLocation(), diag::err_integer_too_large); 3035 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3036 Tok.getLocation()); 3037 } 3038 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3039 } 3040 3041 case LOLR_Raw: { 3042 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3043 // literal is treated as a call of the form 3044 // operator "" X ("n") 3045 unsigned Length = Literal.getUDSuffixOffset(); 3046 QualType StrTy = Context.getConstantArrayType( 3047 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3048 ArrayType::Normal, 0); 3049 Expr *Lit = StringLiteral::Create( 3050 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3051 /*Pascal*/false, StrTy, &TokLoc, 1); 3052 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3053 } 3054 3055 case LOLR_Template: { 3056 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3057 // template), L is treated as a call fo the form 3058 // operator "" X <'c1', 'c2', ... 'ck'>() 3059 // where n is the source character sequence c1 c2 ... ck. 3060 TemplateArgumentListInfo ExplicitArgs; 3061 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3062 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3063 llvm::APSInt Value(CharBits, CharIsUnsigned); 3064 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3065 Value = TokSpelling[I]; 3066 TemplateArgument Arg(Context, Value, Context.CharTy); 3067 TemplateArgumentLocInfo ArgInfo; 3068 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3069 } 3070 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3071 &ExplicitArgs); 3072 } 3073 case LOLR_StringTemplate: 3074 llvm_unreachable("unexpected literal operator lookup result"); 3075 } 3076 } 3077 3078 Expr *Res; 3079 3080 if (Literal.isFloatingLiteral()) { 3081 QualType Ty; 3082 if (Literal.isFloat) 3083 Ty = Context.FloatTy; 3084 else if (!Literal.isLong) 3085 Ty = Context.DoubleTy; 3086 else 3087 Ty = Context.LongDoubleTy; 3088 3089 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3090 3091 if (Ty == Context.DoubleTy) { 3092 if (getLangOpts().SinglePrecisionConstants) { 3093 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3094 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3095 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3096 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3097 } 3098 } 3099 } else if (!Literal.isIntegerLiteral()) { 3100 return ExprError(); 3101 } else { 3102 QualType Ty; 3103 3104 // 'long long' is a C99 or C++11 feature. 3105 if (!getLangOpts().C99 && Literal.isLongLong) { 3106 if (getLangOpts().CPlusPlus) 3107 Diag(Tok.getLocation(), 3108 getLangOpts().CPlusPlus11 ? 3109 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3110 else 3111 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3112 } 3113 3114 // Get the value in the widest-possible width. 3115 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3116 // The microsoft literal suffix extensions support 128-bit literals, which 3117 // may be wider than [u]intmax_t. 3118 // FIXME: Actually, they don't. We seem to have accidentally invented the 3119 // i128 suffix. 3120 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3121 PP.getTargetInfo().hasInt128Type()) 3122 MaxWidth = 128; 3123 llvm::APInt ResultVal(MaxWidth, 0); 3124 3125 if (Literal.GetIntegerValue(ResultVal)) { 3126 // If this value didn't fit into uintmax_t, error and force to ull. 3127 Diag(Tok.getLocation(), diag::err_integer_too_large); 3128 Ty = Context.UnsignedLongLongTy; 3129 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3130 "long long is not intmax_t?"); 3131 } else { 3132 // If this value fits into a ULL, try to figure out what else it fits into 3133 // according to the rules of C99 6.4.4.1p5. 3134 3135 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3136 // be an unsigned int. 3137 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3138 3139 // Check from smallest to largest, picking the smallest type we can. 3140 unsigned Width = 0; 3141 if (!Literal.isLong && !Literal.isLongLong) { 3142 // Are int/unsigned possibilities? 3143 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3144 3145 // Does it fit in a unsigned int? 3146 if (ResultVal.isIntN(IntSize)) { 3147 // Does it fit in a signed int? 3148 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3149 Ty = Context.IntTy; 3150 else if (AllowUnsigned) 3151 Ty = Context.UnsignedIntTy; 3152 Width = IntSize; 3153 } 3154 } 3155 3156 // Are long/unsigned long possibilities? 3157 if (Ty.isNull() && !Literal.isLongLong) { 3158 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3159 3160 // Does it fit in a unsigned long? 3161 if (ResultVal.isIntN(LongSize)) { 3162 // Does it fit in a signed long? 3163 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3164 Ty = Context.LongTy; 3165 else if (AllowUnsigned) 3166 Ty = Context.UnsignedLongTy; 3167 Width = LongSize; 3168 } 3169 } 3170 3171 // Check long long if needed. 3172 if (Ty.isNull()) { 3173 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3174 3175 // Does it fit in a unsigned long long? 3176 if (ResultVal.isIntN(LongLongSize)) { 3177 // Does it fit in a signed long long? 3178 // To be compatible with MSVC, hex integer literals ending with the 3179 // LL or i64 suffix are always signed in Microsoft mode. 3180 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3181 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3182 Ty = Context.LongLongTy; 3183 else if (AllowUnsigned) 3184 Ty = Context.UnsignedLongLongTy; 3185 Width = LongLongSize; 3186 } 3187 } 3188 3189 // If it doesn't fit in unsigned long long, and we're using Microsoft 3190 // extensions, then its a 128-bit integer literal. 3191 if (Ty.isNull() && Literal.isMicrosoftInteger && 3192 PP.getTargetInfo().hasInt128Type()) { 3193 if (Literal.isUnsigned) 3194 Ty = Context.UnsignedInt128Ty; 3195 else 3196 Ty = Context.Int128Ty; 3197 Width = 128; 3198 } 3199 3200 // If we still couldn't decide a type, we probably have something that 3201 // does not fit in a signed long long, but has no U suffix. 3202 if (Ty.isNull()) { 3203 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3204 Ty = Context.UnsignedLongLongTy; 3205 Width = Context.getTargetInfo().getLongLongWidth(); 3206 } 3207 3208 if (ResultVal.getBitWidth() != Width) 3209 ResultVal = ResultVal.trunc(Width); 3210 } 3211 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3212 } 3213 3214 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3215 if (Literal.isImaginary) 3216 Res = new (Context) ImaginaryLiteral(Res, 3217 Context.getComplexType(Res->getType())); 3218 3219 return Owned(Res); 3220} 3221 3222ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3223 assert((E != 0) && "ActOnParenExpr() missing expr"); 3224 return Owned(new (Context) ParenExpr(L, R, E)); 3225} 3226 3227static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3228 SourceLocation Loc, 3229 SourceRange ArgRange) { 3230 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3231 // scalar or vector data type argument..." 3232 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3233 // type (C99 6.2.5p18) or void. 3234 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3235 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3236 << T << ArgRange; 3237 return true; 3238 } 3239 3240 assert((T->isVoidType() || !T->isIncompleteType()) && 3241 "Scalar types should always be complete"); 3242 return false; 3243} 3244 3245static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3246 SourceLocation Loc, 3247 SourceRange ArgRange, 3248 UnaryExprOrTypeTrait TraitKind) { 3249 // Invalid types must be hard errors for SFINAE in C++. 3250 if (S.LangOpts.CPlusPlus) 3251 return true; 3252 3253 // C99 6.5.3.4p1: 3254 if (T->isFunctionType() && 3255 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3256 // sizeof(function)/alignof(function) is allowed as an extension. 3257 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3258 << TraitKind << ArgRange; 3259 return false; 3260 } 3261 3262 // Allow sizeof(void)/alignof(void) as an extension. 3263 if (T->isVoidType()) { 3264 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3265 return false; 3266 } 3267 3268 return true; 3269} 3270 3271static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3272 SourceLocation Loc, 3273 SourceRange ArgRange, 3274 UnaryExprOrTypeTrait TraitKind) { 3275 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3276 // runtime doesn't allow it. 3277 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3278 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3279 << T << (TraitKind == UETT_SizeOf) 3280 << ArgRange; 3281 return true; 3282 } 3283 3284 return false; 3285} 3286 3287/// \brief Check whether E is a pointer from a decayed array type (the decayed 3288/// pointer type is equal to T) and emit a warning if it is. 3289static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3290 Expr *E) { 3291 // Don't warn if the operation changed the type. 3292 if (T != E->getType()) 3293 return; 3294 3295 // Now look for array decays. 3296 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3297 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3298 return; 3299 3300 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3301 << ICE->getType() 3302 << ICE->getSubExpr()->getType(); 3303} 3304 3305/// \brief Check the constrains on expression operands to unary type expression 3306/// and type traits. 3307/// 3308/// Completes any types necessary and validates the constraints on the operand 3309/// expression. The logic mostly mirrors the type-based overload, but may modify 3310/// the expression as it completes the type for that expression through template 3311/// instantiation, etc. 3312bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3313 UnaryExprOrTypeTrait ExprKind) { 3314 QualType ExprTy = E->getType(); 3315 assert(!ExprTy->isReferenceType()); 3316 3317 if (ExprKind == UETT_VecStep) 3318 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3319 E->getSourceRange()); 3320 3321 // Whitelist some types as extensions 3322 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3323 E->getSourceRange(), ExprKind)) 3324 return false; 3325 3326 if (RequireCompleteExprType(E, 3327 diag::err_sizeof_alignof_incomplete_type, 3328 ExprKind, E->getSourceRange())) 3329 return true; 3330 3331 // Completing the expression's type may have changed it. 3332 ExprTy = E->getType(); 3333 assert(!ExprTy->isReferenceType()); 3334 3335 if (ExprTy->isFunctionType()) { 3336 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3337 << ExprKind << E->getSourceRange(); 3338 return true; 3339 } 3340 3341 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3342 E->getSourceRange(), ExprKind)) 3343 return true; 3344 3345 if (ExprKind == UETT_SizeOf) { 3346 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3347 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3348 QualType OType = PVD->getOriginalType(); 3349 QualType Type = PVD->getType(); 3350 if (Type->isPointerType() && OType->isArrayType()) { 3351 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3352 << Type << OType; 3353 Diag(PVD->getLocation(), diag::note_declared_at); 3354 } 3355 } 3356 } 3357 3358 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3359 // decays into a pointer and returns an unintended result. This is most 3360 // likely a typo for "sizeof(array) op x". 3361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3362 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3363 BO->getLHS()); 3364 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3365 BO->getRHS()); 3366 } 3367 } 3368 3369 return false; 3370} 3371 3372/// \brief Check the constraints on operands to unary expression and type 3373/// traits. 3374/// 3375/// This will complete any types necessary, and validate the various constraints 3376/// on those operands. 3377/// 3378/// The UsualUnaryConversions() function is *not* called by this routine. 3379/// C99 6.3.2.1p[2-4] all state: 3380/// Except when it is the operand of the sizeof operator ... 3381/// 3382/// C++ [expr.sizeof]p4 3383/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3384/// standard conversions are not applied to the operand of sizeof. 3385/// 3386/// This policy is followed for all of the unary trait expressions. 3387bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3388 SourceLocation OpLoc, 3389 SourceRange ExprRange, 3390 UnaryExprOrTypeTrait ExprKind) { 3391 if (ExprType->isDependentType()) 3392 return false; 3393 3394 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3395 // the result is the size of the referenced type." 3396 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3397 // result shall be the alignment of the referenced type." 3398 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3399 ExprType = Ref->getPointeeType(); 3400 3401 if (ExprKind == UETT_VecStep) 3402 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3403 3404 // Whitelist some types as extensions 3405 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3406 ExprKind)) 3407 return false; 3408 3409 if (RequireCompleteType(OpLoc, ExprType, 3410 diag::err_sizeof_alignof_incomplete_type, 3411 ExprKind, ExprRange)) 3412 return true; 3413 3414 if (ExprType->isFunctionType()) { 3415 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3416 << ExprKind << ExprRange; 3417 return true; 3418 } 3419 3420 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3421 ExprKind)) 3422 return true; 3423 3424 return false; 3425} 3426 3427static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3428 E = E->IgnoreParens(); 3429 3430 // Cannot know anything else if the expression is dependent. 3431 if (E->isTypeDependent()) 3432 return false; 3433 3434 if (E->getObjectKind() == OK_BitField) { 3435 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3436 << 1 << E->getSourceRange(); 3437 return true; 3438 } 3439 3440 ValueDecl *D = 0; 3441 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3442 D = DRE->getDecl(); 3443 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3444 D = ME->getMemberDecl(); 3445 } 3446 3447 // If it's a field, require the containing struct to have a 3448 // complete definition so that we can compute the layout. 3449 // 3450 // This requires a very particular set of circumstances. For a 3451 // field to be contained within an incomplete type, we must in the 3452 // process of parsing that type. To have an expression refer to a 3453 // field, it must be an id-expression or a member-expression, but 3454 // the latter are always ill-formed when the base type is 3455 // incomplete, including only being partially complete. An 3456 // id-expression can never refer to a field in C because fields 3457 // are not in the ordinary namespace. In C++, an id-expression 3458 // can implicitly be a member access, but only if there's an 3459 // implicit 'this' value, and all such contexts are subject to 3460 // delayed parsing --- except for trailing return types in C++11. 3461 // And if an id-expression referring to a field occurs in a 3462 // context that lacks a 'this' value, it's ill-formed --- except, 3463 // agian, in C++11, where such references are allowed in an 3464 // unevaluated context. So C++11 introduces some new complexity. 3465 // 3466 // For the record, since __alignof__ on expressions is a GCC 3467 // extension, GCC seems to permit this but always gives the 3468 // nonsensical answer 0. 3469 // 3470 // We don't really need the layout here --- we could instead just 3471 // directly check for all the appropriate alignment-lowing 3472 // attributes --- but that would require duplicating a lot of 3473 // logic that just isn't worth duplicating for such a marginal 3474 // use-case. 3475 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3476 // Fast path this check, since we at least know the record has a 3477 // definition if we can find a member of it. 3478 if (!FD->getParent()->isCompleteDefinition()) { 3479 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3480 << E->getSourceRange(); 3481 return true; 3482 } 3483 3484 // Otherwise, if it's a field, and the field doesn't have 3485 // reference type, then it must have a complete type (or be a 3486 // flexible array member, which we explicitly want to 3487 // white-list anyway), which makes the following checks trivial. 3488 if (!FD->getType()->isReferenceType()) 3489 return false; 3490 } 3491 3492 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3493} 3494 3495bool Sema::CheckVecStepExpr(Expr *E) { 3496 E = E->IgnoreParens(); 3497 3498 // Cannot know anything else if the expression is dependent. 3499 if (E->isTypeDependent()) 3500 return false; 3501 3502 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3503} 3504 3505/// \brief Build a sizeof or alignof expression given a type operand. 3506ExprResult 3507Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3508 SourceLocation OpLoc, 3509 UnaryExprOrTypeTrait ExprKind, 3510 SourceRange R) { 3511 if (!TInfo) 3512 return ExprError(); 3513 3514 QualType T = TInfo->getType(); 3515 3516 if (!T->isDependentType() && 3517 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3518 return ExprError(); 3519 3520 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3521 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3522 Context.getSizeType(), 3523 OpLoc, R.getEnd())); 3524} 3525 3526/// \brief Build a sizeof or alignof expression given an expression 3527/// operand. 3528ExprResult 3529Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3530 UnaryExprOrTypeTrait ExprKind) { 3531 ExprResult PE = CheckPlaceholderExpr(E); 3532 if (PE.isInvalid()) 3533 return ExprError(); 3534 3535 E = PE.get(); 3536 3537 // Verify that the operand is valid. 3538 bool isInvalid = false; 3539 if (E->isTypeDependent()) { 3540 // Delay type-checking for type-dependent expressions. 3541 } else if (ExprKind == UETT_AlignOf) { 3542 isInvalid = CheckAlignOfExpr(*this, E); 3543 } else if (ExprKind == UETT_VecStep) { 3544 isInvalid = CheckVecStepExpr(E); 3545 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3546 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3547 isInvalid = true; 3548 } else { 3549 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3550 } 3551 3552 if (isInvalid) 3553 return ExprError(); 3554 3555 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3556 PE = TransformToPotentiallyEvaluated(E); 3557 if (PE.isInvalid()) return ExprError(); 3558 E = PE.take(); 3559 } 3560 3561 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3562 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3563 ExprKind, E, Context.getSizeType(), OpLoc, 3564 E->getSourceRange().getEnd())); 3565} 3566 3567/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3568/// expr and the same for @c alignof and @c __alignof 3569/// Note that the ArgRange is invalid if isType is false. 3570ExprResult 3571Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3572 UnaryExprOrTypeTrait ExprKind, bool IsType, 3573 void *TyOrEx, const SourceRange &ArgRange) { 3574 // If error parsing type, ignore. 3575 if (TyOrEx == 0) return ExprError(); 3576 3577 if (IsType) { 3578 TypeSourceInfo *TInfo; 3579 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3580 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3581 } 3582 3583 Expr *ArgEx = (Expr *)TyOrEx; 3584 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3585 return Result; 3586} 3587 3588static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3589 bool IsReal) { 3590 if (V.get()->isTypeDependent()) 3591 return S.Context.DependentTy; 3592 3593 // _Real and _Imag are only l-values for normal l-values. 3594 if (V.get()->getObjectKind() != OK_Ordinary) { 3595 V = S.DefaultLvalueConversion(V.take()); 3596 if (V.isInvalid()) 3597 return QualType(); 3598 } 3599 3600 // These operators return the element type of a complex type. 3601 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3602 return CT->getElementType(); 3603 3604 // Otherwise they pass through real integer and floating point types here. 3605 if (V.get()->getType()->isArithmeticType()) 3606 return V.get()->getType(); 3607 3608 // Test for placeholders. 3609 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3610 if (PR.isInvalid()) return QualType(); 3611 if (PR.get() != V.get()) { 3612 V = PR; 3613 return CheckRealImagOperand(S, V, Loc, IsReal); 3614 } 3615 3616 // Reject anything else. 3617 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3618 << (IsReal ? "__real" : "__imag"); 3619 return QualType(); 3620} 3621 3622 3623 3624ExprResult 3625Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3626 tok::TokenKind Kind, Expr *Input) { 3627 UnaryOperatorKind Opc; 3628 switch (Kind) { 3629 default: llvm_unreachable("Unknown unary op!"); 3630 case tok::plusplus: Opc = UO_PostInc; break; 3631 case tok::minusminus: Opc = UO_PostDec; break; 3632 } 3633 3634 // Since this might is a postfix expression, get rid of ParenListExprs. 3635 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3636 if (Result.isInvalid()) return ExprError(); 3637 Input = Result.take(); 3638 3639 return BuildUnaryOp(S, OpLoc, Opc, Input); 3640} 3641 3642/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3643/// 3644/// \return true on error 3645static bool checkArithmeticOnObjCPointer(Sema &S, 3646 SourceLocation opLoc, 3647 Expr *op) { 3648 assert(op->getType()->isObjCObjectPointerType()); 3649 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3650 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3651 return false; 3652 3653 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3654 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3655 << op->getSourceRange(); 3656 return true; 3657} 3658 3659ExprResult 3660Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3661 Expr *idx, SourceLocation rbLoc) { 3662 // Since this might be a postfix expression, get rid of ParenListExprs. 3663 if (isa<ParenListExpr>(base)) { 3664 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3665 if (result.isInvalid()) return ExprError(); 3666 base = result.take(); 3667 } 3668 3669 // Handle any non-overload placeholder types in the base and index 3670 // expressions. We can't handle overloads here because the other 3671 // operand might be an overloadable type, in which case the overload 3672 // resolution for the operator overload should get the first crack 3673 // at the overload. 3674 if (base->getType()->isNonOverloadPlaceholderType()) { 3675 ExprResult result = CheckPlaceholderExpr(base); 3676 if (result.isInvalid()) return ExprError(); 3677 base = result.take(); 3678 } 3679 if (idx->getType()->isNonOverloadPlaceholderType()) { 3680 ExprResult result = CheckPlaceholderExpr(idx); 3681 if (result.isInvalid()) return ExprError(); 3682 idx = result.take(); 3683 } 3684 3685 // Build an unanalyzed expression if either operand is type-dependent. 3686 if (getLangOpts().CPlusPlus && 3687 (base->isTypeDependent() || idx->isTypeDependent())) { 3688 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3689 Context.DependentTy, 3690 VK_LValue, OK_Ordinary, 3691 rbLoc)); 3692 } 3693 3694 // Use C++ overloaded-operator rules if either operand has record 3695 // type. The spec says to do this if either type is *overloadable*, 3696 // but enum types can't declare subscript operators or conversion 3697 // operators, so there's nothing interesting for overload resolution 3698 // to do if there aren't any record types involved. 3699 // 3700 // ObjC pointers have their own subscripting logic that is not tied 3701 // to overload resolution and so should not take this path. 3702 if (getLangOpts().CPlusPlus && 3703 (base->getType()->isRecordType() || 3704 (!base->getType()->isObjCObjectPointerType() && 3705 idx->getType()->isRecordType()))) { 3706 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3707 } 3708 3709 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3710} 3711 3712ExprResult 3713Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3714 Expr *Idx, SourceLocation RLoc) { 3715 Expr *LHSExp = Base; 3716 Expr *RHSExp = Idx; 3717 3718 // Perform default conversions. 3719 if (!LHSExp->getType()->getAs<VectorType>()) { 3720 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3721 if (Result.isInvalid()) 3722 return ExprError(); 3723 LHSExp = Result.take(); 3724 } 3725 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3726 if (Result.isInvalid()) 3727 return ExprError(); 3728 RHSExp = Result.take(); 3729 3730 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3731 ExprValueKind VK = VK_LValue; 3732 ExprObjectKind OK = OK_Ordinary; 3733 3734 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3735 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3736 // in the subscript position. As a result, we need to derive the array base 3737 // and index from the expression types. 3738 Expr *BaseExpr, *IndexExpr; 3739 QualType ResultType; 3740 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3741 BaseExpr = LHSExp; 3742 IndexExpr = RHSExp; 3743 ResultType = Context.DependentTy; 3744 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3745 BaseExpr = LHSExp; 3746 IndexExpr = RHSExp; 3747 ResultType = PTy->getPointeeType(); 3748 } else if (const ObjCObjectPointerType *PTy = 3749 LHSTy->getAs<ObjCObjectPointerType>()) { 3750 BaseExpr = LHSExp; 3751 IndexExpr = RHSExp; 3752 3753 // Use custom logic if this should be the pseudo-object subscript 3754 // expression. 3755 if (!LangOpts.isSubscriptPointerArithmetic()) 3756 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3757 3758 ResultType = PTy->getPointeeType(); 3759 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3760 // Handle the uncommon case of "123[Ptr]". 3761 BaseExpr = RHSExp; 3762 IndexExpr = LHSExp; 3763 ResultType = PTy->getPointeeType(); 3764 } else if (const ObjCObjectPointerType *PTy = 3765 RHSTy->getAs<ObjCObjectPointerType>()) { 3766 // Handle the uncommon case of "123[Ptr]". 3767 BaseExpr = RHSExp; 3768 IndexExpr = LHSExp; 3769 ResultType = PTy->getPointeeType(); 3770 if (!LangOpts.isSubscriptPointerArithmetic()) { 3771 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3772 << ResultType << BaseExpr->getSourceRange(); 3773 return ExprError(); 3774 } 3775 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3776 BaseExpr = LHSExp; // vectors: V[123] 3777 IndexExpr = RHSExp; 3778 VK = LHSExp->getValueKind(); 3779 if (VK != VK_RValue) 3780 OK = OK_VectorComponent; 3781 3782 // FIXME: need to deal with const... 3783 ResultType = VTy->getElementType(); 3784 } else if (LHSTy->isArrayType()) { 3785 // If we see an array that wasn't promoted by 3786 // DefaultFunctionArrayLvalueConversion, it must be an array that 3787 // wasn't promoted because of the C90 rule that doesn't 3788 // allow promoting non-lvalue arrays. Warn, then 3789 // force the promotion here. 3790 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3791 LHSExp->getSourceRange(); 3792 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3793 CK_ArrayToPointerDecay).take(); 3794 LHSTy = LHSExp->getType(); 3795 3796 BaseExpr = LHSExp; 3797 IndexExpr = RHSExp; 3798 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3799 } else if (RHSTy->isArrayType()) { 3800 // Same as previous, except for 123[f().a] case 3801 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3802 RHSExp->getSourceRange(); 3803 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3804 CK_ArrayToPointerDecay).take(); 3805 RHSTy = RHSExp->getType(); 3806 3807 BaseExpr = RHSExp; 3808 IndexExpr = LHSExp; 3809 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3810 } else { 3811 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3812 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3813 } 3814 // C99 6.5.2.1p1 3815 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3816 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3817 << IndexExpr->getSourceRange()); 3818 3819 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3820 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3821 && !IndexExpr->isTypeDependent()) 3822 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3823 3824 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3825 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3826 // type. Note that Functions are not objects, and that (in C99 parlance) 3827 // incomplete types are not object types. 3828 if (ResultType->isFunctionType()) { 3829 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3830 << ResultType << BaseExpr->getSourceRange(); 3831 return ExprError(); 3832 } 3833 3834 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3835 // GNU extension: subscripting on pointer to void 3836 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3837 << BaseExpr->getSourceRange(); 3838 3839 // C forbids expressions of unqualified void type from being l-values. 3840 // See IsCForbiddenLValueType. 3841 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3842 } else if (!ResultType->isDependentType() && 3843 RequireCompleteType(LLoc, ResultType, 3844 diag::err_subscript_incomplete_type, BaseExpr)) 3845 return ExprError(); 3846 3847 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3848 !ResultType.isCForbiddenLValueType()); 3849 3850 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3851 ResultType, VK, OK, RLoc)); 3852} 3853 3854ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3855 FunctionDecl *FD, 3856 ParmVarDecl *Param) { 3857 if (Param->hasUnparsedDefaultArg()) { 3858 Diag(CallLoc, 3859 diag::err_use_of_default_argument_to_function_declared_later) << 3860 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3861 Diag(UnparsedDefaultArgLocs[Param], 3862 diag::note_default_argument_declared_here); 3863 return ExprError(); 3864 } 3865 3866 if (Param->hasUninstantiatedDefaultArg()) { 3867 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3868 3869 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3870 Param); 3871 3872 // Instantiate the expression. 3873 MultiLevelTemplateArgumentList MutiLevelArgList 3874 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3875 3876 InstantiatingTemplate Inst(*this, CallLoc, Param, 3877 MutiLevelArgList.getInnermost()); 3878 if (Inst.isInvalid()) 3879 return ExprError(); 3880 3881 ExprResult Result; 3882 { 3883 // C++ [dcl.fct.default]p5: 3884 // The names in the [default argument] expression are bound, and 3885 // the semantic constraints are checked, at the point where the 3886 // default argument expression appears. 3887 ContextRAII SavedContext(*this, FD); 3888 LocalInstantiationScope Local(*this); 3889 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3890 } 3891 if (Result.isInvalid()) 3892 return ExprError(); 3893 3894 // Check the expression as an initializer for the parameter. 3895 InitializedEntity Entity 3896 = InitializedEntity::InitializeParameter(Context, Param); 3897 InitializationKind Kind 3898 = InitializationKind::CreateCopy(Param->getLocation(), 3899 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3900 Expr *ResultE = Result.takeAs<Expr>(); 3901 3902 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3903 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3904 if (Result.isInvalid()) 3905 return ExprError(); 3906 3907 Expr *Arg = Result.takeAs<Expr>(); 3908 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3909 // Build the default argument expression. 3910 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3911 } 3912 3913 // If the default expression creates temporaries, we need to 3914 // push them to the current stack of expression temporaries so they'll 3915 // be properly destroyed. 3916 // FIXME: We should really be rebuilding the default argument with new 3917 // bound temporaries; see the comment in PR5810. 3918 // We don't need to do that with block decls, though, because 3919 // blocks in default argument expression can never capture anything. 3920 if (isa<ExprWithCleanups>(Param->getInit())) { 3921 // Set the "needs cleanups" bit regardless of whether there are 3922 // any explicit objects. 3923 ExprNeedsCleanups = true; 3924 3925 // Append all the objects to the cleanup list. Right now, this 3926 // should always be a no-op, because blocks in default argument 3927 // expressions should never be able to capture anything. 3928 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3929 "default argument expression has capturing blocks?"); 3930 } 3931 3932 // We already type-checked the argument, so we know it works. 3933 // Just mark all of the declarations in this potentially-evaluated expression 3934 // as being "referenced". 3935 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3936 /*SkipLocalVariables=*/true); 3937 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3938} 3939 3940 3941Sema::VariadicCallType 3942Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3943 Expr *Fn) { 3944 if (Proto && Proto->isVariadic()) { 3945 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3946 return VariadicConstructor; 3947 else if (Fn && Fn->getType()->isBlockPointerType()) 3948 return VariadicBlock; 3949 else if (FDecl) { 3950 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3951 if (Method->isInstance()) 3952 return VariadicMethod; 3953 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3954 return VariadicMethod; 3955 return VariadicFunction; 3956 } 3957 return VariadicDoesNotApply; 3958} 3959 3960namespace { 3961class FunctionCallCCC : public FunctionCallFilterCCC { 3962public: 3963 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3964 unsigned NumArgs, bool HasExplicitTemplateArgs) 3965 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3966 FunctionName(FuncName) {} 3967 3968 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 3969 if (!candidate.getCorrectionSpecifier() || 3970 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3971 return false; 3972 } 3973 3974 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3975 } 3976 3977private: 3978 const IdentifierInfo *const FunctionName; 3979}; 3980} 3981 3982static TypoCorrection TryTypoCorrectionForCall(Sema &S, 3983 DeclarationNameInfo FuncName, 3984 ArrayRef<Expr *> Args) { 3985 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 3986 Args.size(), false); 3987 if (TypoCorrection Corrected = 3988 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 3989 S.getScopeForContext(S.CurContext), NULL, CCC)) { 3990 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 3991 if (Corrected.isOverloaded()) { 3992 OverloadCandidateSet OCS(FuncName.getLoc()); 3993 OverloadCandidateSet::iterator Best; 3994 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 3995 CDEnd = Corrected.end(); 3996 CD != CDEnd; ++CD) { 3997 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 3998 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 3999 OCS); 4000 } 4001 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 4002 case OR_Success: 4003 ND = Best->Function; 4004 Corrected.setCorrectionDecl(ND); 4005 break; 4006 default: 4007 break; 4008 } 4009 } 4010 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4011 return Corrected; 4012 } 4013 } 4014 } 4015 return TypoCorrection(); 4016} 4017 4018/// ConvertArgumentsForCall - Converts the arguments specified in 4019/// Args/NumArgs to the parameter types of the function FDecl with 4020/// function prototype Proto. Call is the call expression itself, and 4021/// Fn is the function expression. For a C++ member function, this 4022/// routine does not attempt to convert the object argument. Returns 4023/// true if the call is ill-formed. 4024bool 4025Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4026 FunctionDecl *FDecl, 4027 const FunctionProtoType *Proto, 4028 ArrayRef<Expr *> Args, 4029 SourceLocation RParenLoc, 4030 bool IsExecConfig) { 4031 // Bail out early if calling a builtin with custom typechecking. 4032 // We don't need to do this in the 4033 if (FDecl) 4034 if (unsigned ID = FDecl->getBuiltinID()) 4035 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4036 return false; 4037 4038 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4039 // assignment, to the types of the corresponding parameter, ... 4040 unsigned NumArgsInProto = Proto->getNumArgs(); 4041 bool Invalid = false; 4042 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 4043 unsigned FnKind = Fn->getType()->isBlockPointerType() 4044 ? 1 /* block */ 4045 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4046 : 0 /* function */); 4047 4048 // If too few arguments are available (and we don't have default 4049 // arguments for the remaining parameters), don't make the call. 4050 if (Args.size() < NumArgsInProto) { 4051 if (Args.size() < MinArgs) { 4052 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4053 TypoCorrection TC; 4054 if (FDecl && (TC = TryTypoCorrectionForCall( 4055 *this, DeclarationNameInfo(FDecl->getDeclName(), 4056 (ME ? ME->getMemberLoc() 4057 : Fn->getLocStart())), 4058 Args))) { 4059 unsigned diag_id = 4060 MinArgs == NumArgsInProto && !Proto->isVariadic() 4061 ? diag::err_typecheck_call_too_few_args_suggest 4062 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4063 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4064 << static_cast<unsigned>(Args.size()) 4065 << Fn->getSourceRange()); 4066 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4067 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4068 ? diag::err_typecheck_call_too_few_args_one 4069 : diag::err_typecheck_call_too_few_args_at_least_one) 4070 << FnKind 4071 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4072 else 4073 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4074 ? diag::err_typecheck_call_too_few_args 4075 : diag::err_typecheck_call_too_few_args_at_least) 4076 << FnKind 4077 << MinArgs << static_cast<unsigned>(Args.size()) 4078 << Fn->getSourceRange(); 4079 4080 // Emit the location of the prototype. 4081 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4082 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4083 << FDecl; 4084 4085 return true; 4086 } 4087 Call->setNumArgs(Context, NumArgsInProto); 4088 } 4089 4090 // If too many are passed and not variadic, error on the extras and drop 4091 // them. 4092 if (Args.size() > NumArgsInProto) { 4093 if (!Proto->isVariadic()) { 4094 TypoCorrection TC; 4095 if (FDecl && (TC = TryTypoCorrectionForCall( 4096 *this, DeclarationNameInfo(FDecl->getDeclName(), 4097 Fn->getLocStart()), 4098 Args))) { 4099 unsigned diag_id = 4100 MinArgs == NumArgsInProto && !Proto->isVariadic() 4101 ? diag::err_typecheck_call_too_many_args_suggest 4102 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4103 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto 4104 << static_cast<unsigned>(Args.size()) 4105 << Fn->getSourceRange()); 4106 } else if (NumArgsInProto == 1 && FDecl && 4107 FDecl->getParamDecl(0)->getDeclName()) 4108 Diag(Args[NumArgsInProto]->getLocStart(), 4109 MinArgs == NumArgsInProto 4110 ? diag::err_typecheck_call_too_many_args_one 4111 : diag::err_typecheck_call_too_many_args_at_most_one) 4112 << FnKind 4113 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size()) 4114 << Fn->getSourceRange() 4115 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4116 Args.back()->getLocEnd()); 4117 else 4118 Diag(Args[NumArgsInProto]->getLocStart(), 4119 MinArgs == NumArgsInProto 4120 ? diag::err_typecheck_call_too_many_args 4121 : diag::err_typecheck_call_too_many_args_at_most) 4122 << FnKind 4123 << NumArgsInProto << static_cast<unsigned>(Args.size()) 4124 << Fn->getSourceRange() 4125 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4126 Args.back()->getLocEnd()); 4127 4128 // Emit the location of the prototype. 4129 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4130 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4131 << FDecl; 4132 4133 // This deletes the extra arguments. 4134 Call->setNumArgs(Context, NumArgsInProto); 4135 return true; 4136 } 4137 } 4138 SmallVector<Expr *, 8> AllArgs; 4139 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4140 4141 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4142 Proto, 0, Args, AllArgs, CallType); 4143 if (Invalid) 4144 return true; 4145 unsigned TotalNumArgs = AllArgs.size(); 4146 for (unsigned i = 0; i < TotalNumArgs; ++i) 4147 Call->setArg(i, AllArgs[i]); 4148 4149 return false; 4150} 4151 4152bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 4153 FunctionDecl *FDecl, 4154 const FunctionProtoType *Proto, 4155 unsigned FirstProtoArg, 4156 ArrayRef<Expr *> Args, 4157 SmallVectorImpl<Expr *> &AllArgs, 4158 VariadicCallType CallType, 4159 bool AllowExplicit, 4160 bool IsListInitialization) { 4161 unsigned NumArgsInProto = Proto->getNumArgs(); 4162 unsigned NumArgsToCheck = Args.size(); 4163 bool Invalid = false; 4164 if (Args.size() != NumArgsInProto) 4165 // Use default arguments for missing arguments 4166 NumArgsToCheck = NumArgsInProto; 4167 unsigned ArgIx = 0; 4168 // Continue to check argument types (even if we have too few/many args). 4169 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 4170 QualType ProtoArgType = Proto->getArgType(i); 4171 4172 Expr *Arg; 4173 ParmVarDecl *Param; 4174 if (ArgIx < Args.size()) { 4175 Arg = Args[ArgIx++]; 4176 4177 if (RequireCompleteType(Arg->getLocStart(), 4178 ProtoArgType, 4179 diag::err_call_incomplete_argument, Arg)) 4180 return true; 4181 4182 // Pass the argument 4183 Param = 0; 4184 if (FDecl && i < FDecl->getNumParams()) 4185 Param = FDecl->getParamDecl(i); 4186 4187 // Strip the unbridged-cast placeholder expression off, if applicable. 4188 bool CFAudited = false; 4189 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4190 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4191 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4192 Arg = stripARCUnbridgedCast(Arg); 4193 else if (getLangOpts().ObjCAutoRefCount && 4194 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4195 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4196 CFAudited = true; 4197 4198 InitializedEntity Entity = Param ? 4199 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 4200 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 4201 Proto->isArgConsumed(i)); 4202 4203 // Remember that parameter belongs to a CF audited API. 4204 if (CFAudited) 4205 Entity.setParameterCFAudited(); 4206 4207 ExprResult ArgE = PerformCopyInitialization(Entity, 4208 SourceLocation(), 4209 Owned(Arg), 4210 IsListInitialization, 4211 AllowExplicit); 4212 if (ArgE.isInvalid()) 4213 return true; 4214 4215 Arg = ArgE.takeAs<Expr>(); 4216 } else { 4217 assert(FDecl && "can't use default arguments without a known callee"); 4218 Param = FDecl->getParamDecl(i); 4219 4220 ExprResult ArgExpr = 4221 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4222 if (ArgExpr.isInvalid()) 4223 return true; 4224 4225 Arg = ArgExpr.takeAs<Expr>(); 4226 } 4227 4228 // Check for array bounds violations for each argument to the call. This 4229 // check only triggers warnings when the argument isn't a more complex Expr 4230 // with its own checking, such as a BinaryOperator. 4231 CheckArrayAccess(Arg); 4232 4233 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4234 CheckStaticArrayArgument(CallLoc, Param, Arg); 4235 4236 AllArgs.push_back(Arg); 4237 } 4238 4239 // If this is a variadic call, handle args passed through "...". 4240 if (CallType != VariadicDoesNotApply) { 4241 // Assume that extern "C" functions with variadic arguments that 4242 // return __unknown_anytype aren't *really* variadic. 4243 if (Proto->getResultType() == Context.UnknownAnyTy && 4244 FDecl && FDecl->isExternC()) { 4245 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4246 QualType paramType; // ignored 4247 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4248 Invalid |= arg.isInvalid(); 4249 AllArgs.push_back(arg.take()); 4250 } 4251 4252 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4253 } else { 4254 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4255 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4256 FDecl); 4257 Invalid |= Arg.isInvalid(); 4258 AllArgs.push_back(Arg.take()); 4259 } 4260 } 4261 4262 // Check for array bounds violations. 4263 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4264 CheckArrayAccess(Args[i]); 4265 } 4266 return Invalid; 4267} 4268 4269static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4270 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4271 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4272 TL = DTL.getOriginalLoc(); 4273 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4274 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4275 << ATL.getLocalSourceRange(); 4276} 4277 4278/// CheckStaticArrayArgument - If the given argument corresponds to a static 4279/// array parameter, check that it is non-null, and that if it is formed by 4280/// array-to-pointer decay, the underlying array is sufficiently large. 4281/// 4282/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4283/// array type derivation, then for each call to the function, the value of the 4284/// corresponding actual argument shall provide access to the first element of 4285/// an array with at least as many elements as specified by the size expression. 4286void 4287Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4288 ParmVarDecl *Param, 4289 const Expr *ArgExpr) { 4290 // Static array parameters are not supported in C++. 4291 if (!Param || getLangOpts().CPlusPlus) 4292 return; 4293 4294 QualType OrigTy = Param->getOriginalType(); 4295 4296 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4297 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4298 return; 4299 4300 if (ArgExpr->isNullPointerConstant(Context, 4301 Expr::NPC_NeverValueDependent)) { 4302 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4303 DiagnoseCalleeStaticArrayParam(*this, Param); 4304 return; 4305 } 4306 4307 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4308 if (!CAT) 4309 return; 4310 4311 const ConstantArrayType *ArgCAT = 4312 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4313 if (!ArgCAT) 4314 return; 4315 4316 if (ArgCAT->getSize().ult(CAT->getSize())) { 4317 Diag(CallLoc, diag::warn_static_array_too_small) 4318 << ArgExpr->getSourceRange() 4319 << (unsigned) ArgCAT->getSize().getZExtValue() 4320 << (unsigned) CAT->getSize().getZExtValue(); 4321 DiagnoseCalleeStaticArrayParam(*this, Param); 4322 } 4323} 4324 4325/// Given a function expression of unknown-any type, try to rebuild it 4326/// to have a function type. 4327static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4328 4329/// Is the given type a placeholder that we need to lower out 4330/// immediately during argument processing? 4331static bool isPlaceholderToRemoveAsArg(QualType type) { 4332 // Placeholders are never sugared. 4333 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4334 if (!placeholder) return false; 4335 4336 switch (placeholder->getKind()) { 4337 // Ignore all the non-placeholder types. 4338#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4339#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4340#include "clang/AST/BuiltinTypes.def" 4341 return false; 4342 4343 // We cannot lower out overload sets; they might validly be resolved 4344 // by the call machinery. 4345 case BuiltinType::Overload: 4346 return false; 4347 4348 // Unbridged casts in ARC can be handled in some call positions and 4349 // should be left in place. 4350 case BuiltinType::ARCUnbridgedCast: 4351 return false; 4352 4353 // Pseudo-objects should be converted as soon as possible. 4354 case BuiltinType::PseudoObject: 4355 return true; 4356 4357 // The debugger mode could theoretically but currently does not try 4358 // to resolve unknown-typed arguments based on known parameter types. 4359 case BuiltinType::UnknownAny: 4360 return true; 4361 4362 // These are always invalid as call arguments and should be reported. 4363 case BuiltinType::BoundMember: 4364 case BuiltinType::BuiltinFn: 4365 return true; 4366 } 4367 llvm_unreachable("bad builtin type kind"); 4368} 4369 4370/// Check an argument list for placeholders that we won't try to 4371/// handle later. 4372static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4373 // Apply this processing to all the arguments at once instead of 4374 // dying at the first failure. 4375 bool hasInvalid = false; 4376 for (size_t i = 0, e = args.size(); i != e; i++) { 4377 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4378 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4379 if (result.isInvalid()) hasInvalid = true; 4380 else args[i] = result.take(); 4381 } 4382 } 4383 return hasInvalid; 4384} 4385 4386/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4387/// This provides the location of the left/right parens and a list of comma 4388/// locations. 4389ExprResult 4390Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4391 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4392 Expr *ExecConfig, bool IsExecConfig) { 4393 // Since this might be a postfix expression, get rid of ParenListExprs. 4394 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4395 if (Result.isInvalid()) return ExprError(); 4396 Fn = Result.take(); 4397 4398 if (checkArgsForPlaceholders(*this, ArgExprs)) 4399 return ExprError(); 4400 4401 if (getLangOpts().CPlusPlus) { 4402 // If this is a pseudo-destructor expression, build the call immediately. 4403 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4404 if (!ArgExprs.empty()) { 4405 // Pseudo-destructor calls should not have any arguments. 4406 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4407 << FixItHint::CreateRemoval( 4408 SourceRange(ArgExprs[0]->getLocStart(), 4409 ArgExprs.back()->getLocEnd())); 4410 } 4411 4412 return Owned(new (Context) CallExpr(Context, Fn, None, 4413 Context.VoidTy, VK_RValue, 4414 RParenLoc)); 4415 } 4416 if (Fn->getType() == Context.PseudoObjectTy) { 4417 ExprResult result = CheckPlaceholderExpr(Fn); 4418 if (result.isInvalid()) return ExprError(); 4419 Fn = result.take(); 4420 } 4421 4422 // Determine whether this is a dependent call inside a C++ template, 4423 // in which case we won't do any semantic analysis now. 4424 // FIXME: Will need to cache the results of name lookup (including ADL) in 4425 // Fn. 4426 bool Dependent = false; 4427 if (Fn->isTypeDependent()) 4428 Dependent = true; 4429 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4430 Dependent = true; 4431 4432 if (Dependent) { 4433 if (ExecConfig) { 4434 return Owned(new (Context) CUDAKernelCallExpr( 4435 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4436 Context.DependentTy, VK_RValue, RParenLoc)); 4437 } else { 4438 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4439 Context.DependentTy, VK_RValue, 4440 RParenLoc)); 4441 } 4442 } 4443 4444 // Determine whether this is a call to an object (C++ [over.call.object]). 4445 if (Fn->getType()->isRecordType()) 4446 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4447 ArgExprs, RParenLoc)); 4448 4449 if (Fn->getType() == Context.UnknownAnyTy) { 4450 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4451 if (result.isInvalid()) return ExprError(); 4452 Fn = result.take(); 4453 } 4454 4455 if (Fn->getType() == Context.BoundMemberTy) { 4456 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4457 } 4458 } 4459 4460 // Check for overloaded calls. This can happen even in C due to extensions. 4461 if (Fn->getType() == Context.OverloadTy) { 4462 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4463 4464 // We aren't supposed to apply this logic for if there's an '&' involved. 4465 if (!find.HasFormOfMemberPointer) { 4466 OverloadExpr *ovl = find.Expression; 4467 if (isa<UnresolvedLookupExpr>(ovl)) { 4468 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4469 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4470 RParenLoc, ExecConfig); 4471 } else { 4472 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4473 RParenLoc); 4474 } 4475 } 4476 } 4477 4478 // If we're directly calling a function, get the appropriate declaration. 4479 if (Fn->getType() == Context.UnknownAnyTy) { 4480 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4481 if (result.isInvalid()) return ExprError(); 4482 Fn = result.take(); 4483 } 4484 4485 Expr *NakedFn = Fn->IgnoreParens(); 4486 4487 NamedDecl *NDecl = 0; 4488 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4489 if (UnOp->getOpcode() == UO_AddrOf) 4490 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4491 4492 if (isa<DeclRefExpr>(NakedFn)) 4493 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4494 else if (isa<MemberExpr>(NakedFn)) 4495 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4496 4497 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4498 ExecConfig, IsExecConfig); 4499} 4500 4501ExprResult 4502Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4503 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4504 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4505 if (!ConfigDecl) 4506 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4507 << "cudaConfigureCall"); 4508 QualType ConfigQTy = ConfigDecl->getType(); 4509 4510 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4511 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4512 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4513 4514 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4515 /*IsExecConfig=*/true); 4516} 4517 4518/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4519/// 4520/// __builtin_astype( value, dst type ) 4521/// 4522ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4523 SourceLocation BuiltinLoc, 4524 SourceLocation RParenLoc) { 4525 ExprValueKind VK = VK_RValue; 4526 ExprObjectKind OK = OK_Ordinary; 4527 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4528 QualType SrcTy = E->getType(); 4529 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4530 return ExprError(Diag(BuiltinLoc, 4531 diag::err_invalid_astype_of_different_size) 4532 << DstTy 4533 << SrcTy 4534 << E->getSourceRange()); 4535 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4536 RParenLoc)); 4537} 4538 4539/// ActOnConvertVectorExpr - create a new convert-vector expression from the 4540/// provided arguments. 4541/// 4542/// __builtin_convertvector( value, dst type ) 4543/// 4544ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4545 SourceLocation BuiltinLoc, 4546 SourceLocation RParenLoc) { 4547 TypeSourceInfo *TInfo; 4548 GetTypeFromParser(ParsedDestTy, &TInfo); 4549 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4550} 4551 4552/// BuildResolvedCallExpr - Build a call to a resolved expression, 4553/// i.e. an expression not of \p OverloadTy. The expression should 4554/// unary-convert to an expression of function-pointer or 4555/// block-pointer type. 4556/// 4557/// \param NDecl the declaration being called, if available 4558ExprResult 4559Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4560 SourceLocation LParenLoc, 4561 ArrayRef<Expr *> Args, 4562 SourceLocation RParenLoc, 4563 Expr *Config, bool IsExecConfig) { 4564 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4565 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4566 4567 // Promote the function operand. 4568 // We special-case function promotion here because we only allow promoting 4569 // builtin functions to function pointers in the callee of a call. 4570 ExprResult Result; 4571 if (BuiltinID && 4572 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4573 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4574 CK_BuiltinFnToFnPtr).take(); 4575 } else { 4576 Result = UsualUnaryConversions(Fn); 4577 } 4578 if (Result.isInvalid()) 4579 return ExprError(); 4580 Fn = Result.take(); 4581 4582 // Make the call expr early, before semantic checks. This guarantees cleanup 4583 // of arguments and function on error. 4584 CallExpr *TheCall; 4585 if (Config) 4586 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4587 cast<CallExpr>(Config), Args, 4588 Context.BoolTy, VK_RValue, 4589 RParenLoc); 4590 else 4591 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4592 VK_RValue, RParenLoc); 4593 4594 // Bail out early if calling a builtin with custom typechecking. 4595 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4596 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4597 4598 retry: 4599 const FunctionType *FuncT; 4600 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4601 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4602 // have type pointer to function". 4603 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4604 if (FuncT == 0) 4605 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4606 << Fn->getType() << Fn->getSourceRange()); 4607 } else if (const BlockPointerType *BPT = 4608 Fn->getType()->getAs<BlockPointerType>()) { 4609 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4610 } else { 4611 // Handle calls to expressions of unknown-any type. 4612 if (Fn->getType() == Context.UnknownAnyTy) { 4613 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4614 if (rewrite.isInvalid()) return ExprError(); 4615 Fn = rewrite.take(); 4616 TheCall->setCallee(Fn); 4617 goto retry; 4618 } 4619 4620 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4621 << Fn->getType() << Fn->getSourceRange()); 4622 } 4623 4624 if (getLangOpts().CUDA) { 4625 if (Config) { 4626 // CUDA: Kernel calls must be to global functions 4627 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4628 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4629 << FDecl->getName() << Fn->getSourceRange()); 4630 4631 // CUDA: Kernel function must have 'void' return type 4632 if (!FuncT->getResultType()->isVoidType()) 4633 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4634 << Fn->getType() << Fn->getSourceRange()); 4635 } else { 4636 // CUDA: Calls to global functions must be configured 4637 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4638 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4639 << FDecl->getName() << Fn->getSourceRange()); 4640 } 4641 } 4642 4643 // Check for a valid return type 4644 if (CheckCallReturnType(FuncT->getResultType(), 4645 Fn->getLocStart(), TheCall, 4646 FDecl)) 4647 return ExprError(); 4648 4649 // We know the result type of the call, set it. 4650 TheCall->setType(FuncT->getCallResultType(Context)); 4651 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4652 4653 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4654 if (Proto) { 4655 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4656 IsExecConfig)) 4657 return ExprError(); 4658 } else { 4659 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4660 4661 if (FDecl) { 4662 // Check if we have too few/too many template arguments, based 4663 // on our knowledge of the function definition. 4664 const FunctionDecl *Def = 0; 4665 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4666 Proto = Def->getType()->getAs<FunctionProtoType>(); 4667 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4668 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4669 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4670 } 4671 4672 // If the function we're calling isn't a function prototype, but we have 4673 // a function prototype from a prior declaratiom, use that prototype. 4674 if (!FDecl->hasPrototype()) 4675 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4676 } 4677 4678 // Promote the arguments (C99 6.5.2.2p6). 4679 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4680 Expr *Arg = Args[i]; 4681 4682 if (Proto && i < Proto->getNumArgs()) { 4683 InitializedEntity Entity 4684 = InitializedEntity::InitializeParameter(Context, 4685 Proto->getArgType(i), 4686 Proto->isArgConsumed(i)); 4687 ExprResult ArgE = PerformCopyInitialization(Entity, 4688 SourceLocation(), 4689 Owned(Arg)); 4690 if (ArgE.isInvalid()) 4691 return true; 4692 4693 Arg = ArgE.takeAs<Expr>(); 4694 4695 } else { 4696 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4697 4698 if (ArgE.isInvalid()) 4699 return true; 4700 4701 Arg = ArgE.takeAs<Expr>(); 4702 } 4703 4704 if (RequireCompleteType(Arg->getLocStart(), 4705 Arg->getType(), 4706 diag::err_call_incomplete_argument, Arg)) 4707 return ExprError(); 4708 4709 TheCall->setArg(i, Arg); 4710 } 4711 } 4712 4713 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4714 if (!Method->isStatic()) 4715 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4716 << Fn->getSourceRange()); 4717 4718 // Check for sentinels 4719 if (NDecl) 4720 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4721 4722 // Do special checking on direct calls to functions. 4723 if (FDecl) { 4724 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4725 return ExprError(); 4726 4727 if (BuiltinID) 4728 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4729 } else if (NDecl) { 4730 if (CheckPointerCall(NDecl, TheCall, Proto)) 4731 return ExprError(); 4732 } else { 4733 if (CheckOtherCall(TheCall, Proto)) 4734 return ExprError(); 4735 } 4736 4737 return MaybeBindToTemporary(TheCall); 4738} 4739 4740ExprResult 4741Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4742 SourceLocation RParenLoc, Expr *InitExpr) { 4743 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4744 // FIXME: put back this assert when initializers are worked out. 4745 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4746 4747 TypeSourceInfo *TInfo; 4748 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4749 if (!TInfo) 4750 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4751 4752 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4753} 4754 4755ExprResult 4756Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4757 SourceLocation RParenLoc, Expr *LiteralExpr) { 4758 QualType literalType = TInfo->getType(); 4759 4760 if (literalType->isArrayType()) { 4761 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4762 diag::err_illegal_decl_array_incomplete_type, 4763 SourceRange(LParenLoc, 4764 LiteralExpr->getSourceRange().getEnd()))) 4765 return ExprError(); 4766 if (literalType->isVariableArrayType()) 4767 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4768 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4769 } else if (!literalType->isDependentType() && 4770 RequireCompleteType(LParenLoc, literalType, 4771 diag::err_typecheck_decl_incomplete_type, 4772 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4773 return ExprError(); 4774 4775 InitializedEntity Entity 4776 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4777 InitializationKind Kind 4778 = InitializationKind::CreateCStyleCast(LParenLoc, 4779 SourceRange(LParenLoc, RParenLoc), 4780 /*InitList=*/true); 4781 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4782 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4783 &literalType); 4784 if (Result.isInvalid()) 4785 return ExprError(); 4786 LiteralExpr = Result.get(); 4787 4788 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4789 if (isFileScope && 4790 !LiteralExpr->isTypeDependent() && 4791 !LiteralExpr->isValueDependent() && 4792 !literalType->isDependentType()) { // 6.5.2.5p3 4793 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4794 return ExprError(); 4795 } 4796 4797 // In C, compound literals are l-values for some reason. 4798 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4799 4800 return MaybeBindToTemporary( 4801 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4802 VK, LiteralExpr, isFileScope)); 4803} 4804 4805ExprResult 4806Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4807 SourceLocation RBraceLoc) { 4808 // Immediately handle non-overload placeholders. Overloads can be 4809 // resolved contextually, but everything else here can't. 4810 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4811 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4812 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4813 4814 // Ignore failures; dropping the entire initializer list because 4815 // of one failure would be terrible for indexing/etc. 4816 if (result.isInvalid()) continue; 4817 4818 InitArgList[I] = result.take(); 4819 } 4820 } 4821 4822 // Semantic analysis for initializers is done by ActOnDeclarator() and 4823 // CheckInitializer() - it requires knowledge of the object being intialized. 4824 4825 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4826 RBraceLoc); 4827 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4828 return Owned(E); 4829} 4830 4831/// Do an explicit extend of the given block pointer if we're in ARC. 4832static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4833 assert(E.get()->getType()->isBlockPointerType()); 4834 assert(E.get()->isRValue()); 4835 4836 // Only do this in an r-value context. 4837 if (!S.getLangOpts().ObjCAutoRefCount) return; 4838 4839 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4840 CK_ARCExtendBlockObject, E.get(), 4841 /*base path*/ 0, VK_RValue); 4842 S.ExprNeedsCleanups = true; 4843} 4844 4845/// Prepare a conversion of the given expression to an ObjC object 4846/// pointer type. 4847CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4848 QualType type = E.get()->getType(); 4849 if (type->isObjCObjectPointerType()) { 4850 return CK_BitCast; 4851 } else if (type->isBlockPointerType()) { 4852 maybeExtendBlockObject(*this, E); 4853 return CK_BlockPointerToObjCPointerCast; 4854 } else { 4855 assert(type->isPointerType()); 4856 return CK_CPointerToObjCPointerCast; 4857 } 4858} 4859 4860/// Prepares for a scalar cast, performing all the necessary stages 4861/// except the final cast and returning the kind required. 4862CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4863 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4864 // Also, callers should have filtered out the invalid cases with 4865 // pointers. Everything else should be possible. 4866 4867 QualType SrcTy = Src.get()->getType(); 4868 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4869 return CK_NoOp; 4870 4871 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4872 case Type::STK_MemberPointer: 4873 llvm_unreachable("member pointer type in C"); 4874 4875 case Type::STK_CPointer: 4876 case Type::STK_BlockPointer: 4877 case Type::STK_ObjCObjectPointer: 4878 switch (DestTy->getScalarTypeKind()) { 4879 case Type::STK_CPointer: 4880 return CK_BitCast; 4881 case Type::STK_BlockPointer: 4882 return (SrcKind == Type::STK_BlockPointer 4883 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4884 case Type::STK_ObjCObjectPointer: 4885 if (SrcKind == Type::STK_ObjCObjectPointer) 4886 return CK_BitCast; 4887 if (SrcKind == Type::STK_CPointer) 4888 return CK_CPointerToObjCPointerCast; 4889 maybeExtendBlockObject(*this, Src); 4890 return CK_BlockPointerToObjCPointerCast; 4891 case Type::STK_Bool: 4892 return CK_PointerToBoolean; 4893 case Type::STK_Integral: 4894 return CK_PointerToIntegral; 4895 case Type::STK_Floating: 4896 case Type::STK_FloatingComplex: 4897 case Type::STK_IntegralComplex: 4898 case Type::STK_MemberPointer: 4899 llvm_unreachable("illegal cast from pointer"); 4900 } 4901 llvm_unreachable("Should have returned before this"); 4902 4903 case Type::STK_Bool: // casting from bool is like casting from an integer 4904 case Type::STK_Integral: 4905 switch (DestTy->getScalarTypeKind()) { 4906 case Type::STK_CPointer: 4907 case Type::STK_ObjCObjectPointer: 4908 case Type::STK_BlockPointer: 4909 if (Src.get()->isNullPointerConstant(Context, 4910 Expr::NPC_ValueDependentIsNull)) 4911 return CK_NullToPointer; 4912 return CK_IntegralToPointer; 4913 case Type::STK_Bool: 4914 return CK_IntegralToBoolean; 4915 case Type::STK_Integral: 4916 return CK_IntegralCast; 4917 case Type::STK_Floating: 4918 return CK_IntegralToFloating; 4919 case Type::STK_IntegralComplex: 4920 Src = ImpCastExprToType(Src.take(), 4921 DestTy->castAs<ComplexType>()->getElementType(), 4922 CK_IntegralCast); 4923 return CK_IntegralRealToComplex; 4924 case Type::STK_FloatingComplex: 4925 Src = ImpCastExprToType(Src.take(), 4926 DestTy->castAs<ComplexType>()->getElementType(), 4927 CK_IntegralToFloating); 4928 return CK_FloatingRealToComplex; 4929 case Type::STK_MemberPointer: 4930 llvm_unreachable("member pointer type in C"); 4931 } 4932 llvm_unreachable("Should have returned before this"); 4933 4934 case Type::STK_Floating: 4935 switch (DestTy->getScalarTypeKind()) { 4936 case Type::STK_Floating: 4937 return CK_FloatingCast; 4938 case Type::STK_Bool: 4939 return CK_FloatingToBoolean; 4940 case Type::STK_Integral: 4941 return CK_FloatingToIntegral; 4942 case Type::STK_FloatingComplex: 4943 Src = ImpCastExprToType(Src.take(), 4944 DestTy->castAs<ComplexType>()->getElementType(), 4945 CK_FloatingCast); 4946 return CK_FloatingRealToComplex; 4947 case Type::STK_IntegralComplex: 4948 Src = ImpCastExprToType(Src.take(), 4949 DestTy->castAs<ComplexType>()->getElementType(), 4950 CK_FloatingToIntegral); 4951 return CK_IntegralRealToComplex; 4952 case Type::STK_CPointer: 4953 case Type::STK_ObjCObjectPointer: 4954 case Type::STK_BlockPointer: 4955 llvm_unreachable("valid float->pointer cast?"); 4956 case Type::STK_MemberPointer: 4957 llvm_unreachable("member pointer type in C"); 4958 } 4959 llvm_unreachable("Should have returned before this"); 4960 4961 case Type::STK_FloatingComplex: 4962 switch (DestTy->getScalarTypeKind()) { 4963 case Type::STK_FloatingComplex: 4964 return CK_FloatingComplexCast; 4965 case Type::STK_IntegralComplex: 4966 return CK_FloatingComplexToIntegralComplex; 4967 case Type::STK_Floating: { 4968 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4969 if (Context.hasSameType(ET, DestTy)) 4970 return CK_FloatingComplexToReal; 4971 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4972 return CK_FloatingCast; 4973 } 4974 case Type::STK_Bool: 4975 return CK_FloatingComplexToBoolean; 4976 case Type::STK_Integral: 4977 Src = ImpCastExprToType(Src.take(), 4978 SrcTy->castAs<ComplexType>()->getElementType(), 4979 CK_FloatingComplexToReal); 4980 return CK_FloatingToIntegral; 4981 case Type::STK_CPointer: 4982 case Type::STK_ObjCObjectPointer: 4983 case Type::STK_BlockPointer: 4984 llvm_unreachable("valid complex float->pointer cast?"); 4985 case Type::STK_MemberPointer: 4986 llvm_unreachable("member pointer type in C"); 4987 } 4988 llvm_unreachable("Should have returned before this"); 4989 4990 case Type::STK_IntegralComplex: 4991 switch (DestTy->getScalarTypeKind()) { 4992 case Type::STK_FloatingComplex: 4993 return CK_IntegralComplexToFloatingComplex; 4994 case Type::STK_IntegralComplex: 4995 return CK_IntegralComplexCast; 4996 case Type::STK_Integral: { 4997 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4998 if (Context.hasSameType(ET, DestTy)) 4999 return CK_IntegralComplexToReal; 5000 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 5001 return CK_IntegralCast; 5002 } 5003 case Type::STK_Bool: 5004 return CK_IntegralComplexToBoolean; 5005 case Type::STK_Floating: 5006 Src = ImpCastExprToType(Src.take(), 5007 SrcTy->castAs<ComplexType>()->getElementType(), 5008 CK_IntegralComplexToReal); 5009 return CK_IntegralToFloating; 5010 case Type::STK_CPointer: 5011 case Type::STK_ObjCObjectPointer: 5012 case Type::STK_BlockPointer: 5013 llvm_unreachable("valid complex int->pointer cast?"); 5014 case Type::STK_MemberPointer: 5015 llvm_unreachable("member pointer type in C"); 5016 } 5017 llvm_unreachable("Should have returned before this"); 5018 } 5019 5020 llvm_unreachable("Unhandled scalar cast"); 5021} 5022 5023bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5024 CastKind &Kind) { 5025 assert(VectorTy->isVectorType() && "Not a vector type!"); 5026 5027 if (Ty->isVectorType() || Ty->isIntegerType()) { 5028 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 5029 return Diag(R.getBegin(), 5030 Ty->isVectorType() ? 5031 diag::err_invalid_conversion_between_vectors : 5032 diag::err_invalid_conversion_between_vector_and_integer) 5033 << VectorTy << Ty << R; 5034 } else 5035 return Diag(R.getBegin(), 5036 diag::err_invalid_conversion_between_vector_and_scalar) 5037 << VectorTy << Ty << R; 5038 5039 Kind = CK_BitCast; 5040 return false; 5041} 5042 5043ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5044 Expr *CastExpr, CastKind &Kind) { 5045 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5046 5047 QualType SrcTy = CastExpr->getType(); 5048 5049 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5050 // an ExtVectorType. 5051 // In OpenCL, casts between vectors of different types are not allowed. 5052 // (See OpenCL 6.2). 5053 if (SrcTy->isVectorType()) { 5054 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 5055 || (getLangOpts().OpenCL && 5056 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5057 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5058 << DestTy << SrcTy << R; 5059 return ExprError(); 5060 } 5061 Kind = CK_BitCast; 5062 return Owned(CastExpr); 5063 } 5064 5065 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5066 // conversion will take place first from scalar to elt type, and then 5067 // splat from elt type to vector. 5068 if (SrcTy->isPointerType()) 5069 return Diag(R.getBegin(), 5070 diag::err_invalid_conversion_between_vector_and_scalar) 5071 << DestTy << SrcTy << R; 5072 5073 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5074 ExprResult CastExprRes = Owned(CastExpr); 5075 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5076 if (CastExprRes.isInvalid()) 5077 return ExprError(); 5078 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5079 5080 Kind = CK_VectorSplat; 5081 return Owned(CastExpr); 5082} 5083 5084ExprResult 5085Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5086 Declarator &D, ParsedType &Ty, 5087 SourceLocation RParenLoc, Expr *CastExpr) { 5088 assert(!D.isInvalidType() && (CastExpr != 0) && 5089 "ActOnCastExpr(): missing type or expr"); 5090 5091 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5092 if (D.isInvalidType()) 5093 return ExprError(); 5094 5095 if (getLangOpts().CPlusPlus) { 5096 // Check that there are no default arguments (C++ only). 5097 CheckExtraCXXDefaultArguments(D); 5098 } 5099 5100 checkUnusedDeclAttributes(D); 5101 5102 QualType castType = castTInfo->getType(); 5103 Ty = CreateParsedType(castType, castTInfo); 5104 5105 bool isVectorLiteral = false; 5106 5107 // Check for an altivec or OpenCL literal, 5108 // i.e. all the elements are integer constants. 5109 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5110 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5111 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5112 && castType->isVectorType() && (PE || PLE)) { 5113 if (PLE && PLE->getNumExprs() == 0) { 5114 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5115 return ExprError(); 5116 } 5117 if (PE || PLE->getNumExprs() == 1) { 5118 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5119 if (!E->getType()->isVectorType()) 5120 isVectorLiteral = true; 5121 } 5122 else 5123 isVectorLiteral = true; 5124 } 5125 5126 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5127 // then handle it as such. 5128 if (isVectorLiteral) 5129 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5130 5131 // If the Expr being casted is a ParenListExpr, handle it specially. 5132 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5133 // sequence of BinOp comma operators. 5134 if (isa<ParenListExpr>(CastExpr)) { 5135 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5136 if (Result.isInvalid()) return ExprError(); 5137 CastExpr = Result.take(); 5138 } 5139 5140 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5141} 5142 5143ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5144 SourceLocation RParenLoc, Expr *E, 5145 TypeSourceInfo *TInfo) { 5146 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5147 "Expected paren or paren list expression"); 5148 5149 Expr **exprs; 5150 unsigned numExprs; 5151 Expr *subExpr; 5152 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5153 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5154 LiteralLParenLoc = PE->getLParenLoc(); 5155 LiteralRParenLoc = PE->getRParenLoc(); 5156 exprs = PE->getExprs(); 5157 numExprs = PE->getNumExprs(); 5158 } else { // isa<ParenExpr> by assertion at function entrance 5159 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5160 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5161 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5162 exprs = &subExpr; 5163 numExprs = 1; 5164 } 5165 5166 QualType Ty = TInfo->getType(); 5167 assert(Ty->isVectorType() && "Expected vector type"); 5168 5169 SmallVector<Expr *, 8> initExprs; 5170 const VectorType *VTy = Ty->getAs<VectorType>(); 5171 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5172 5173 // '(...)' form of vector initialization in AltiVec: the number of 5174 // initializers must be one or must match the size of the vector. 5175 // If a single value is specified in the initializer then it will be 5176 // replicated to all the components of the vector 5177 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5178 // The number of initializers must be one or must match the size of the 5179 // vector. If a single value is specified in the initializer then it will 5180 // be replicated to all the components of the vector 5181 if (numExprs == 1) { 5182 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5183 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5184 if (Literal.isInvalid()) 5185 return ExprError(); 5186 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5187 PrepareScalarCast(Literal, ElemTy)); 5188 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5189 } 5190 else if (numExprs < numElems) { 5191 Diag(E->getExprLoc(), 5192 diag::err_incorrect_number_of_vector_initializers); 5193 return ExprError(); 5194 } 5195 else 5196 initExprs.append(exprs, exprs + numExprs); 5197 } 5198 else { 5199 // For OpenCL, when the number of initializers is a single value, 5200 // it will be replicated to all components of the vector. 5201 if (getLangOpts().OpenCL && 5202 VTy->getVectorKind() == VectorType::GenericVector && 5203 numExprs == 1) { 5204 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5205 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5206 if (Literal.isInvalid()) 5207 return ExprError(); 5208 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5209 PrepareScalarCast(Literal, ElemTy)); 5210 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5211 } 5212 5213 initExprs.append(exprs, exprs + numExprs); 5214 } 5215 // FIXME: This means that pretty-printing the final AST will produce curly 5216 // braces instead of the original commas. 5217 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5218 initExprs, LiteralRParenLoc); 5219 initE->setType(Ty); 5220 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5221} 5222 5223/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5224/// the ParenListExpr into a sequence of comma binary operators. 5225ExprResult 5226Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5227 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5228 if (!E) 5229 return Owned(OrigExpr); 5230 5231 ExprResult Result(E->getExpr(0)); 5232 5233 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5234 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5235 E->getExpr(i)); 5236 5237 if (Result.isInvalid()) return ExprError(); 5238 5239 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5240} 5241 5242ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5243 SourceLocation R, 5244 MultiExprArg Val) { 5245 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5246 return Owned(expr); 5247} 5248 5249/// \brief Emit a specialized diagnostic when one expression is a null pointer 5250/// constant and the other is not a pointer. Returns true if a diagnostic is 5251/// emitted. 5252bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5253 SourceLocation QuestionLoc) { 5254 Expr *NullExpr = LHSExpr; 5255 Expr *NonPointerExpr = RHSExpr; 5256 Expr::NullPointerConstantKind NullKind = 5257 NullExpr->isNullPointerConstant(Context, 5258 Expr::NPC_ValueDependentIsNotNull); 5259 5260 if (NullKind == Expr::NPCK_NotNull) { 5261 NullExpr = RHSExpr; 5262 NonPointerExpr = LHSExpr; 5263 NullKind = 5264 NullExpr->isNullPointerConstant(Context, 5265 Expr::NPC_ValueDependentIsNotNull); 5266 } 5267 5268 if (NullKind == Expr::NPCK_NotNull) 5269 return false; 5270 5271 if (NullKind == Expr::NPCK_ZeroExpression) 5272 return false; 5273 5274 if (NullKind == Expr::NPCK_ZeroLiteral) { 5275 // In this case, check to make sure that we got here from a "NULL" 5276 // string in the source code. 5277 NullExpr = NullExpr->IgnoreParenImpCasts(); 5278 SourceLocation loc = NullExpr->getExprLoc(); 5279 if (!findMacroSpelling(loc, "NULL")) 5280 return false; 5281 } 5282 5283 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5284 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5285 << NonPointerExpr->getType() << DiagType 5286 << NonPointerExpr->getSourceRange(); 5287 return true; 5288} 5289 5290/// \brief Return false if the condition expression is valid, true otherwise. 5291static bool checkCondition(Sema &S, Expr *Cond) { 5292 QualType CondTy = Cond->getType(); 5293 5294 // C99 6.5.15p2 5295 if (CondTy->isScalarType()) return false; 5296 5297 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5298 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5299 return false; 5300 5301 // Emit the proper error message. 5302 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5303 diag::err_typecheck_cond_expect_scalar : 5304 diag::err_typecheck_cond_expect_scalar_or_vector) 5305 << CondTy; 5306 return true; 5307} 5308 5309/// \brief Return false if the two expressions can be converted to a vector, 5310/// true otherwise 5311static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5312 ExprResult &RHS, 5313 QualType CondTy) { 5314 // Both operands should be of scalar type. 5315 if (!LHS.get()->getType()->isScalarType()) { 5316 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5317 << CondTy; 5318 return true; 5319 } 5320 if (!RHS.get()->getType()->isScalarType()) { 5321 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5322 << CondTy; 5323 return true; 5324 } 5325 5326 // Implicity convert these scalars to the type of the condition. 5327 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5328 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5329 return false; 5330} 5331 5332/// \brief Handle when one or both operands are void type. 5333static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5334 ExprResult &RHS) { 5335 Expr *LHSExpr = LHS.get(); 5336 Expr *RHSExpr = RHS.get(); 5337 5338 if (!LHSExpr->getType()->isVoidType()) 5339 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5340 << RHSExpr->getSourceRange(); 5341 if (!RHSExpr->getType()->isVoidType()) 5342 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5343 << LHSExpr->getSourceRange(); 5344 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5345 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5346 return S.Context.VoidTy; 5347} 5348 5349/// \brief Return false if the NullExpr can be promoted to PointerTy, 5350/// true otherwise. 5351static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5352 QualType PointerTy) { 5353 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5354 !NullExpr.get()->isNullPointerConstant(S.Context, 5355 Expr::NPC_ValueDependentIsNull)) 5356 return true; 5357 5358 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5359 return false; 5360} 5361 5362/// \brief Checks compatibility between two pointers and return the resulting 5363/// type. 5364static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5365 ExprResult &RHS, 5366 SourceLocation Loc) { 5367 QualType LHSTy = LHS.get()->getType(); 5368 QualType RHSTy = RHS.get()->getType(); 5369 5370 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5371 // Two identical pointers types are always compatible. 5372 return LHSTy; 5373 } 5374 5375 QualType lhptee, rhptee; 5376 5377 // Get the pointee types. 5378 bool IsBlockPointer = false; 5379 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5380 lhptee = LHSBTy->getPointeeType(); 5381 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5382 IsBlockPointer = true; 5383 } else { 5384 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5385 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5386 } 5387 5388 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5389 // differently qualified versions of compatible types, the result type is 5390 // a pointer to an appropriately qualified version of the composite 5391 // type. 5392 5393 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5394 // clause doesn't make sense for our extensions. E.g. address space 2 should 5395 // be incompatible with address space 3: they may live on different devices or 5396 // anything. 5397 Qualifiers lhQual = lhptee.getQualifiers(); 5398 Qualifiers rhQual = rhptee.getQualifiers(); 5399 5400 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5401 lhQual.removeCVRQualifiers(); 5402 rhQual.removeCVRQualifiers(); 5403 5404 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5405 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5406 5407 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5408 5409 if (CompositeTy.isNull()) { 5410 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5411 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5412 << RHS.get()->getSourceRange(); 5413 // In this situation, we assume void* type. No especially good 5414 // reason, but this is what gcc does, and we do have to pick 5415 // to get a consistent AST. 5416 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5417 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5418 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5419 return incompatTy; 5420 } 5421 5422 // The pointer types are compatible. 5423 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5424 if (IsBlockPointer) 5425 ResultTy = S.Context.getBlockPointerType(ResultTy); 5426 else 5427 ResultTy = S.Context.getPointerType(ResultTy); 5428 5429 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5430 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5431 return ResultTy; 5432} 5433 5434/// \brief Return the resulting type when the operands are both block pointers. 5435static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5436 ExprResult &LHS, 5437 ExprResult &RHS, 5438 SourceLocation Loc) { 5439 QualType LHSTy = LHS.get()->getType(); 5440 QualType RHSTy = RHS.get()->getType(); 5441 5442 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5443 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5444 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5445 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5446 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5447 return destType; 5448 } 5449 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5450 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5451 << RHS.get()->getSourceRange(); 5452 return QualType(); 5453 } 5454 5455 // We have 2 block pointer types. 5456 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5457} 5458 5459/// \brief Return the resulting type when the operands are both pointers. 5460static QualType 5461checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5462 ExprResult &RHS, 5463 SourceLocation Loc) { 5464 // get the pointer types 5465 QualType LHSTy = LHS.get()->getType(); 5466 QualType RHSTy = RHS.get()->getType(); 5467 5468 // get the "pointed to" types 5469 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5470 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5471 5472 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5473 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5474 // Figure out necessary qualifiers (C99 6.5.15p6) 5475 QualType destPointee 5476 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5477 QualType destType = S.Context.getPointerType(destPointee); 5478 // Add qualifiers if necessary. 5479 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5480 // Promote to void*. 5481 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5482 return destType; 5483 } 5484 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5485 QualType destPointee 5486 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5487 QualType destType = S.Context.getPointerType(destPointee); 5488 // Add qualifiers if necessary. 5489 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5490 // Promote to void*. 5491 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5492 return destType; 5493 } 5494 5495 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5496} 5497 5498/// \brief Return false if the first expression is not an integer and the second 5499/// expression is not a pointer, true otherwise. 5500static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5501 Expr* PointerExpr, SourceLocation Loc, 5502 bool IsIntFirstExpr) { 5503 if (!PointerExpr->getType()->isPointerType() || 5504 !Int.get()->getType()->isIntegerType()) 5505 return false; 5506 5507 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5508 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5509 5510 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5511 << Expr1->getType() << Expr2->getType() 5512 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5513 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5514 CK_IntegralToPointer); 5515 return true; 5516} 5517 5518/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5519/// In that case, LHS = cond. 5520/// C99 6.5.15 5521QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5522 ExprResult &RHS, ExprValueKind &VK, 5523 ExprObjectKind &OK, 5524 SourceLocation QuestionLoc) { 5525 5526 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5527 if (!LHSResult.isUsable()) return QualType(); 5528 LHS = LHSResult; 5529 5530 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5531 if (!RHSResult.isUsable()) return QualType(); 5532 RHS = RHSResult; 5533 5534 // C++ is sufficiently different to merit its own checker. 5535 if (getLangOpts().CPlusPlus) 5536 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5537 5538 VK = VK_RValue; 5539 OK = OK_Ordinary; 5540 5541 // First, check the condition. 5542 Cond = UsualUnaryConversions(Cond.take()); 5543 if (Cond.isInvalid()) 5544 return QualType(); 5545 if (checkCondition(*this, Cond.get())) 5546 return QualType(); 5547 5548 // Now check the two expressions. 5549 if (LHS.get()->getType()->isVectorType() || 5550 RHS.get()->getType()->isVectorType()) 5551 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5552 5553 UsualArithmeticConversions(LHS, RHS); 5554 if (LHS.isInvalid() || RHS.isInvalid()) 5555 return QualType(); 5556 5557 QualType CondTy = Cond.get()->getType(); 5558 QualType LHSTy = LHS.get()->getType(); 5559 QualType RHSTy = RHS.get()->getType(); 5560 5561 // If the condition is a vector, and both operands are scalar, 5562 // attempt to implicity convert them to the vector type to act like the 5563 // built in select. (OpenCL v1.1 s6.3.i) 5564 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5565 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5566 return QualType(); 5567 5568 // If both operands have arithmetic type, do the usual arithmetic conversions 5569 // to find a common type: C99 6.5.15p3,5. 5570 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5571 return LHS.get()->getType(); 5572 5573 // If both operands are the same structure or union type, the result is that 5574 // type. 5575 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5576 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5577 if (LHSRT->getDecl() == RHSRT->getDecl()) 5578 // "If both the operands have structure or union type, the result has 5579 // that type." This implies that CV qualifiers are dropped. 5580 return LHSTy.getUnqualifiedType(); 5581 // FIXME: Type of conditional expression must be complete in C mode. 5582 } 5583 5584 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5585 // The following || allows only one side to be void (a GCC-ism). 5586 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5587 return checkConditionalVoidType(*this, LHS, RHS); 5588 } 5589 5590 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5591 // the type of the other operand." 5592 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5593 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5594 5595 // All objective-c pointer type analysis is done here. 5596 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5597 QuestionLoc); 5598 if (LHS.isInvalid() || RHS.isInvalid()) 5599 return QualType(); 5600 if (!compositeType.isNull()) 5601 return compositeType; 5602 5603 5604 // Handle block pointer types. 5605 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5606 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5607 QuestionLoc); 5608 5609 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5610 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5611 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5612 QuestionLoc); 5613 5614 // GCC compatibility: soften pointer/integer mismatch. Note that 5615 // null pointers have been filtered out by this point. 5616 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5617 /*isIntFirstExpr=*/true)) 5618 return RHSTy; 5619 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5620 /*isIntFirstExpr=*/false)) 5621 return LHSTy; 5622 5623 // Emit a better diagnostic if one of the expressions is a null pointer 5624 // constant and the other is not a pointer type. In this case, the user most 5625 // likely forgot to take the address of the other expression. 5626 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5627 return QualType(); 5628 5629 // Otherwise, the operands are not compatible. 5630 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5631 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5632 << RHS.get()->getSourceRange(); 5633 return QualType(); 5634} 5635 5636/// FindCompositeObjCPointerType - Helper method to find composite type of 5637/// two objective-c pointer types of the two input expressions. 5638QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5639 SourceLocation QuestionLoc) { 5640 QualType LHSTy = LHS.get()->getType(); 5641 QualType RHSTy = RHS.get()->getType(); 5642 5643 // Handle things like Class and struct objc_class*. Here we case the result 5644 // to the pseudo-builtin, because that will be implicitly cast back to the 5645 // redefinition type if an attempt is made to access its fields. 5646 if (LHSTy->isObjCClassType() && 5647 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5648 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5649 return LHSTy; 5650 } 5651 if (RHSTy->isObjCClassType() && 5652 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5653 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5654 return RHSTy; 5655 } 5656 // And the same for struct objc_object* / id 5657 if (LHSTy->isObjCIdType() && 5658 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5659 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5660 return LHSTy; 5661 } 5662 if (RHSTy->isObjCIdType() && 5663 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5664 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5665 return RHSTy; 5666 } 5667 // And the same for struct objc_selector* / SEL 5668 if (Context.isObjCSelType(LHSTy) && 5669 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5670 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5671 return LHSTy; 5672 } 5673 if (Context.isObjCSelType(RHSTy) && 5674 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5675 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5676 return RHSTy; 5677 } 5678 // Check constraints for Objective-C object pointers types. 5679 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5680 5681 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5682 // Two identical object pointer types are always compatible. 5683 return LHSTy; 5684 } 5685 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5686 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5687 QualType compositeType = LHSTy; 5688 5689 // If both operands are interfaces and either operand can be 5690 // assigned to the other, use that type as the composite 5691 // type. This allows 5692 // xxx ? (A*) a : (B*) b 5693 // where B is a subclass of A. 5694 // 5695 // Additionally, as for assignment, if either type is 'id' 5696 // allow silent coercion. Finally, if the types are 5697 // incompatible then make sure to use 'id' as the composite 5698 // type so the result is acceptable for sending messages to. 5699 5700 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5701 // It could return the composite type. 5702 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5703 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5704 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5705 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5706 } else if ((LHSTy->isObjCQualifiedIdType() || 5707 RHSTy->isObjCQualifiedIdType()) && 5708 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5709 // Need to handle "id<xx>" explicitly. 5710 // GCC allows qualified id and any Objective-C type to devolve to 5711 // id. Currently localizing to here until clear this should be 5712 // part of ObjCQualifiedIdTypesAreCompatible. 5713 compositeType = Context.getObjCIdType(); 5714 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5715 compositeType = Context.getObjCIdType(); 5716 } else if (!(compositeType = 5717 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5718 ; 5719 else { 5720 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5721 << LHSTy << RHSTy 5722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5723 QualType incompatTy = Context.getObjCIdType(); 5724 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5725 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5726 return incompatTy; 5727 } 5728 // The object pointer types are compatible. 5729 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5730 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5731 return compositeType; 5732 } 5733 // Check Objective-C object pointer types and 'void *' 5734 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5735 if (getLangOpts().ObjCAutoRefCount) { 5736 // ARC forbids the implicit conversion of object pointers to 'void *', 5737 // so these types are not compatible. 5738 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5740 LHS = RHS = true; 5741 return QualType(); 5742 } 5743 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5744 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5745 QualType destPointee 5746 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5747 QualType destType = Context.getPointerType(destPointee); 5748 // Add qualifiers if necessary. 5749 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5750 // Promote to void*. 5751 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5752 return destType; 5753 } 5754 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5755 if (getLangOpts().ObjCAutoRefCount) { 5756 // ARC forbids the implicit conversion of object pointers to 'void *', 5757 // so these types are not compatible. 5758 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5759 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5760 LHS = RHS = true; 5761 return QualType(); 5762 } 5763 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5764 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5765 QualType destPointee 5766 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5767 QualType destType = Context.getPointerType(destPointee); 5768 // Add qualifiers if necessary. 5769 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5770 // Promote to void*. 5771 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5772 return destType; 5773 } 5774 return QualType(); 5775} 5776 5777/// SuggestParentheses - Emit a note with a fixit hint that wraps 5778/// ParenRange in parentheses. 5779static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5780 const PartialDiagnostic &Note, 5781 SourceRange ParenRange) { 5782 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5783 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5784 EndLoc.isValid()) { 5785 Self.Diag(Loc, Note) 5786 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5787 << FixItHint::CreateInsertion(EndLoc, ")"); 5788 } else { 5789 // We can't display the parentheses, so just show the bare note. 5790 Self.Diag(Loc, Note) << ParenRange; 5791 } 5792} 5793 5794static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5795 return Opc >= BO_Mul && Opc <= BO_Shr; 5796} 5797 5798/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5799/// expression, either using a built-in or overloaded operator, 5800/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5801/// expression. 5802static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5803 Expr **RHSExprs) { 5804 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5805 E = E->IgnoreImpCasts(); 5806 E = E->IgnoreConversionOperator(); 5807 E = E->IgnoreImpCasts(); 5808 5809 // Built-in binary operator. 5810 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5811 if (IsArithmeticOp(OP->getOpcode())) { 5812 *Opcode = OP->getOpcode(); 5813 *RHSExprs = OP->getRHS(); 5814 return true; 5815 } 5816 } 5817 5818 // Overloaded operator. 5819 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5820 if (Call->getNumArgs() != 2) 5821 return false; 5822 5823 // Make sure this is really a binary operator that is safe to pass into 5824 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5825 OverloadedOperatorKind OO = Call->getOperator(); 5826 if (OO < OO_Plus || OO > OO_Arrow || 5827 OO == OO_PlusPlus || OO == OO_MinusMinus) 5828 return false; 5829 5830 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5831 if (IsArithmeticOp(OpKind)) { 5832 *Opcode = OpKind; 5833 *RHSExprs = Call->getArg(1); 5834 return true; 5835 } 5836 } 5837 5838 return false; 5839} 5840 5841static bool IsLogicOp(BinaryOperatorKind Opc) { 5842 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5843} 5844 5845/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5846/// or is a logical expression such as (x==y) which has int type, but is 5847/// commonly interpreted as boolean. 5848static bool ExprLooksBoolean(Expr *E) { 5849 E = E->IgnoreParenImpCasts(); 5850 5851 if (E->getType()->isBooleanType()) 5852 return true; 5853 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5854 return IsLogicOp(OP->getOpcode()); 5855 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5856 return OP->getOpcode() == UO_LNot; 5857 5858 return false; 5859} 5860 5861/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5862/// and binary operator are mixed in a way that suggests the programmer assumed 5863/// the conditional operator has higher precedence, for example: 5864/// "int x = a + someBinaryCondition ? 1 : 2". 5865static void DiagnoseConditionalPrecedence(Sema &Self, 5866 SourceLocation OpLoc, 5867 Expr *Condition, 5868 Expr *LHSExpr, 5869 Expr *RHSExpr) { 5870 BinaryOperatorKind CondOpcode; 5871 Expr *CondRHS; 5872 5873 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5874 return; 5875 if (!ExprLooksBoolean(CondRHS)) 5876 return; 5877 5878 // The condition is an arithmetic binary expression, with a right- 5879 // hand side that looks boolean, so warn. 5880 5881 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5882 << Condition->getSourceRange() 5883 << BinaryOperator::getOpcodeStr(CondOpcode); 5884 5885 SuggestParentheses(Self, OpLoc, 5886 Self.PDiag(diag::note_precedence_silence) 5887 << BinaryOperator::getOpcodeStr(CondOpcode), 5888 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5889 5890 SuggestParentheses(Self, OpLoc, 5891 Self.PDiag(diag::note_precedence_conditional_first), 5892 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5893} 5894 5895/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5896/// in the case of a the GNU conditional expr extension. 5897ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5898 SourceLocation ColonLoc, 5899 Expr *CondExpr, Expr *LHSExpr, 5900 Expr *RHSExpr) { 5901 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5902 // was the condition. 5903 OpaqueValueExpr *opaqueValue = 0; 5904 Expr *commonExpr = 0; 5905 if (LHSExpr == 0) { 5906 commonExpr = CondExpr; 5907 // Lower out placeholder types first. This is important so that we don't 5908 // try to capture a placeholder. This happens in few cases in C++; such 5909 // as Objective-C++'s dictionary subscripting syntax. 5910 if (commonExpr->hasPlaceholderType()) { 5911 ExprResult result = CheckPlaceholderExpr(commonExpr); 5912 if (!result.isUsable()) return ExprError(); 5913 commonExpr = result.take(); 5914 } 5915 // We usually want to apply unary conversions *before* saving, except 5916 // in the special case of a C++ l-value conditional. 5917 if (!(getLangOpts().CPlusPlus 5918 && !commonExpr->isTypeDependent() 5919 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5920 && commonExpr->isGLValue() 5921 && commonExpr->isOrdinaryOrBitFieldObject() 5922 && RHSExpr->isOrdinaryOrBitFieldObject() 5923 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5924 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5925 if (commonRes.isInvalid()) 5926 return ExprError(); 5927 commonExpr = commonRes.take(); 5928 } 5929 5930 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5931 commonExpr->getType(), 5932 commonExpr->getValueKind(), 5933 commonExpr->getObjectKind(), 5934 commonExpr); 5935 LHSExpr = CondExpr = opaqueValue; 5936 } 5937 5938 ExprValueKind VK = VK_RValue; 5939 ExprObjectKind OK = OK_Ordinary; 5940 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5941 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5942 VK, OK, QuestionLoc); 5943 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5944 RHS.isInvalid()) 5945 return ExprError(); 5946 5947 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5948 RHS.get()); 5949 5950 if (!commonExpr) 5951 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5952 LHS.take(), ColonLoc, 5953 RHS.take(), result, VK, OK)); 5954 5955 return Owned(new (Context) 5956 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5957 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5958 OK)); 5959} 5960 5961// checkPointerTypesForAssignment - This is a very tricky routine (despite 5962// being closely modeled after the C99 spec:-). The odd characteristic of this 5963// routine is it effectively iqnores the qualifiers on the top level pointee. 5964// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5965// FIXME: add a couple examples in this comment. 5966static Sema::AssignConvertType 5967checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5968 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5969 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5970 5971 // get the "pointed to" type (ignoring qualifiers at the top level) 5972 const Type *lhptee, *rhptee; 5973 Qualifiers lhq, rhq; 5974 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5975 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5976 5977 Sema::AssignConvertType ConvTy = Sema::Compatible; 5978 5979 // C99 6.5.16.1p1: This following citation is common to constraints 5980 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5981 // qualifiers of the type *pointed to* by the right; 5982 Qualifiers lq; 5983 5984 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5985 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5986 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5987 // Ignore lifetime for further calculation. 5988 lhq.removeObjCLifetime(); 5989 rhq.removeObjCLifetime(); 5990 } 5991 5992 if (!lhq.compatiblyIncludes(rhq)) { 5993 // Treat address-space mismatches as fatal. TODO: address subspaces 5994 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5995 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5996 5997 // It's okay to add or remove GC or lifetime qualifiers when converting to 5998 // and from void*. 5999 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6000 .compatiblyIncludes( 6001 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6002 && (lhptee->isVoidType() || rhptee->isVoidType())) 6003 ; // keep old 6004 6005 // Treat lifetime mismatches as fatal. 6006 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6007 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6008 6009 // For GCC compatibility, other qualifier mismatches are treated 6010 // as still compatible in C. 6011 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6012 } 6013 6014 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6015 // incomplete type and the other is a pointer to a qualified or unqualified 6016 // version of void... 6017 if (lhptee->isVoidType()) { 6018 if (rhptee->isIncompleteOrObjectType()) 6019 return ConvTy; 6020 6021 // As an extension, we allow cast to/from void* to function pointer. 6022 assert(rhptee->isFunctionType()); 6023 return Sema::FunctionVoidPointer; 6024 } 6025 6026 if (rhptee->isVoidType()) { 6027 if (lhptee->isIncompleteOrObjectType()) 6028 return ConvTy; 6029 6030 // As an extension, we allow cast to/from void* to function pointer. 6031 assert(lhptee->isFunctionType()); 6032 return Sema::FunctionVoidPointer; 6033 } 6034 6035 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6036 // unqualified versions of compatible types, ... 6037 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6038 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6039 // Check if the pointee types are compatible ignoring the sign. 6040 // We explicitly check for char so that we catch "char" vs 6041 // "unsigned char" on systems where "char" is unsigned. 6042 if (lhptee->isCharType()) 6043 ltrans = S.Context.UnsignedCharTy; 6044 else if (lhptee->hasSignedIntegerRepresentation()) 6045 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6046 6047 if (rhptee->isCharType()) 6048 rtrans = S.Context.UnsignedCharTy; 6049 else if (rhptee->hasSignedIntegerRepresentation()) 6050 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6051 6052 if (ltrans == rtrans) { 6053 // Types are compatible ignoring the sign. Qualifier incompatibility 6054 // takes priority over sign incompatibility because the sign 6055 // warning can be disabled. 6056 if (ConvTy != Sema::Compatible) 6057 return ConvTy; 6058 6059 return Sema::IncompatiblePointerSign; 6060 } 6061 6062 // If we are a multi-level pointer, it's possible that our issue is simply 6063 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6064 // the eventual target type is the same and the pointers have the same 6065 // level of indirection, this must be the issue. 6066 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6067 do { 6068 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6069 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6070 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6071 6072 if (lhptee == rhptee) 6073 return Sema::IncompatibleNestedPointerQualifiers; 6074 } 6075 6076 // General pointer incompatibility takes priority over qualifiers. 6077 return Sema::IncompatiblePointer; 6078 } 6079 if (!S.getLangOpts().CPlusPlus && 6080 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6081 return Sema::IncompatiblePointer; 6082 return ConvTy; 6083} 6084 6085/// checkBlockPointerTypesForAssignment - This routine determines whether two 6086/// block pointer types are compatible or whether a block and normal pointer 6087/// are compatible. It is more restrict than comparing two function pointer 6088// types. 6089static Sema::AssignConvertType 6090checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6091 QualType RHSType) { 6092 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6093 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6094 6095 QualType lhptee, rhptee; 6096 6097 // get the "pointed to" type (ignoring qualifiers at the top level) 6098 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6099 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6100 6101 // In C++, the types have to match exactly. 6102 if (S.getLangOpts().CPlusPlus) 6103 return Sema::IncompatibleBlockPointer; 6104 6105 Sema::AssignConvertType ConvTy = Sema::Compatible; 6106 6107 // For blocks we enforce that qualifiers are identical. 6108 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6109 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6110 6111 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6112 return Sema::IncompatibleBlockPointer; 6113 6114 return ConvTy; 6115} 6116 6117/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6118/// for assignment compatibility. 6119static Sema::AssignConvertType 6120checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6121 QualType RHSType) { 6122 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6123 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6124 6125 if (LHSType->isObjCBuiltinType()) { 6126 // Class is not compatible with ObjC object pointers. 6127 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6128 !RHSType->isObjCQualifiedClassType()) 6129 return Sema::IncompatiblePointer; 6130 return Sema::Compatible; 6131 } 6132 if (RHSType->isObjCBuiltinType()) { 6133 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6134 !LHSType->isObjCQualifiedClassType()) 6135 return Sema::IncompatiblePointer; 6136 return Sema::Compatible; 6137 } 6138 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6139 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6140 6141 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6142 // make an exception for id<P> 6143 !LHSType->isObjCQualifiedIdType()) 6144 return Sema::CompatiblePointerDiscardsQualifiers; 6145 6146 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6147 return Sema::Compatible; 6148 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6149 return Sema::IncompatibleObjCQualifiedId; 6150 return Sema::IncompatiblePointer; 6151} 6152 6153Sema::AssignConvertType 6154Sema::CheckAssignmentConstraints(SourceLocation Loc, 6155 QualType LHSType, QualType RHSType) { 6156 // Fake up an opaque expression. We don't actually care about what 6157 // cast operations are required, so if CheckAssignmentConstraints 6158 // adds casts to this they'll be wasted, but fortunately that doesn't 6159 // usually happen on valid code. 6160 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6161 ExprResult RHSPtr = &RHSExpr; 6162 CastKind K = CK_Invalid; 6163 6164 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6165} 6166 6167/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6168/// has code to accommodate several GCC extensions when type checking 6169/// pointers. Here are some objectionable examples that GCC considers warnings: 6170/// 6171/// int a, *pint; 6172/// short *pshort; 6173/// struct foo *pfoo; 6174/// 6175/// pint = pshort; // warning: assignment from incompatible pointer type 6176/// a = pint; // warning: assignment makes integer from pointer without a cast 6177/// pint = a; // warning: assignment makes pointer from integer without a cast 6178/// pint = pfoo; // warning: assignment from incompatible pointer type 6179/// 6180/// As a result, the code for dealing with pointers is more complex than the 6181/// C99 spec dictates. 6182/// 6183/// Sets 'Kind' for any result kind except Incompatible. 6184Sema::AssignConvertType 6185Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6186 CastKind &Kind) { 6187 QualType RHSType = RHS.get()->getType(); 6188 QualType OrigLHSType = LHSType; 6189 6190 // Get canonical types. We're not formatting these types, just comparing 6191 // them. 6192 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6193 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6194 6195 // Common case: no conversion required. 6196 if (LHSType == RHSType) { 6197 Kind = CK_NoOp; 6198 return Compatible; 6199 } 6200 6201 // If we have an atomic type, try a non-atomic assignment, then just add an 6202 // atomic qualification step. 6203 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6204 Sema::AssignConvertType result = 6205 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6206 if (result != Compatible) 6207 return result; 6208 if (Kind != CK_NoOp) 6209 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6210 Kind = CK_NonAtomicToAtomic; 6211 return Compatible; 6212 } 6213 6214 // If the left-hand side is a reference type, then we are in a 6215 // (rare!) case where we've allowed the use of references in C, 6216 // e.g., as a parameter type in a built-in function. In this case, 6217 // just make sure that the type referenced is compatible with the 6218 // right-hand side type. The caller is responsible for adjusting 6219 // LHSType so that the resulting expression does not have reference 6220 // type. 6221 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6222 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6223 Kind = CK_LValueBitCast; 6224 return Compatible; 6225 } 6226 return Incompatible; 6227 } 6228 6229 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6230 // to the same ExtVector type. 6231 if (LHSType->isExtVectorType()) { 6232 if (RHSType->isExtVectorType()) 6233 return Incompatible; 6234 if (RHSType->isArithmeticType()) { 6235 // CK_VectorSplat does T -> vector T, so first cast to the 6236 // element type. 6237 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6238 if (elType != RHSType) { 6239 Kind = PrepareScalarCast(RHS, elType); 6240 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6241 } 6242 Kind = CK_VectorSplat; 6243 return Compatible; 6244 } 6245 } 6246 6247 // Conversions to or from vector type. 6248 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6249 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6250 // Allow assignments of an AltiVec vector type to an equivalent GCC 6251 // vector type and vice versa 6252 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6253 Kind = CK_BitCast; 6254 return Compatible; 6255 } 6256 6257 // If we are allowing lax vector conversions, and LHS and RHS are both 6258 // vectors, the total size only needs to be the same. This is a bitcast; 6259 // no bits are changed but the result type is different. 6260 if (getLangOpts().LaxVectorConversions && 6261 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 6262 Kind = CK_BitCast; 6263 return IncompatibleVectors; 6264 } 6265 } 6266 return Incompatible; 6267 } 6268 6269 // Arithmetic conversions. 6270 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6271 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6272 Kind = PrepareScalarCast(RHS, LHSType); 6273 return Compatible; 6274 } 6275 6276 // Conversions to normal pointers. 6277 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6278 // U* -> T* 6279 if (isa<PointerType>(RHSType)) { 6280 Kind = CK_BitCast; 6281 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6282 } 6283 6284 // int -> T* 6285 if (RHSType->isIntegerType()) { 6286 Kind = CK_IntegralToPointer; // FIXME: null? 6287 return IntToPointer; 6288 } 6289 6290 // C pointers are not compatible with ObjC object pointers, 6291 // with two exceptions: 6292 if (isa<ObjCObjectPointerType>(RHSType)) { 6293 // - conversions to void* 6294 if (LHSPointer->getPointeeType()->isVoidType()) { 6295 Kind = CK_BitCast; 6296 return Compatible; 6297 } 6298 6299 // - conversions from 'Class' to the redefinition type 6300 if (RHSType->isObjCClassType() && 6301 Context.hasSameType(LHSType, 6302 Context.getObjCClassRedefinitionType())) { 6303 Kind = CK_BitCast; 6304 return Compatible; 6305 } 6306 6307 Kind = CK_BitCast; 6308 return IncompatiblePointer; 6309 } 6310 6311 // U^ -> void* 6312 if (RHSType->getAs<BlockPointerType>()) { 6313 if (LHSPointer->getPointeeType()->isVoidType()) { 6314 Kind = CK_BitCast; 6315 return Compatible; 6316 } 6317 } 6318 6319 return Incompatible; 6320 } 6321 6322 // Conversions to block pointers. 6323 if (isa<BlockPointerType>(LHSType)) { 6324 // U^ -> T^ 6325 if (RHSType->isBlockPointerType()) { 6326 Kind = CK_BitCast; 6327 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6328 } 6329 6330 // int or null -> T^ 6331 if (RHSType->isIntegerType()) { 6332 Kind = CK_IntegralToPointer; // FIXME: null 6333 return IntToBlockPointer; 6334 } 6335 6336 // id -> T^ 6337 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6338 Kind = CK_AnyPointerToBlockPointerCast; 6339 return Compatible; 6340 } 6341 6342 // void* -> T^ 6343 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6344 if (RHSPT->getPointeeType()->isVoidType()) { 6345 Kind = CK_AnyPointerToBlockPointerCast; 6346 return Compatible; 6347 } 6348 6349 return Incompatible; 6350 } 6351 6352 // Conversions to Objective-C pointers. 6353 if (isa<ObjCObjectPointerType>(LHSType)) { 6354 // A* -> B* 6355 if (RHSType->isObjCObjectPointerType()) { 6356 Kind = CK_BitCast; 6357 Sema::AssignConvertType result = 6358 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6359 if (getLangOpts().ObjCAutoRefCount && 6360 result == Compatible && 6361 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6362 result = IncompatibleObjCWeakRef; 6363 return result; 6364 } 6365 6366 // int or null -> A* 6367 if (RHSType->isIntegerType()) { 6368 Kind = CK_IntegralToPointer; // FIXME: null 6369 return IntToPointer; 6370 } 6371 6372 // In general, C pointers are not compatible with ObjC object pointers, 6373 // with two exceptions: 6374 if (isa<PointerType>(RHSType)) { 6375 Kind = CK_CPointerToObjCPointerCast; 6376 6377 // - conversions from 'void*' 6378 if (RHSType->isVoidPointerType()) { 6379 return Compatible; 6380 } 6381 6382 // - conversions to 'Class' from its redefinition type 6383 if (LHSType->isObjCClassType() && 6384 Context.hasSameType(RHSType, 6385 Context.getObjCClassRedefinitionType())) { 6386 return Compatible; 6387 } 6388 6389 return IncompatiblePointer; 6390 } 6391 6392 // T^ -> A* 6393 if (RHSType->isBlockPointerType()) { 6394 maybeExtendBlockObject(*this, RHS); 6395 Kind = CK_BlockPointerToObjCPointerCast; 6396 return Compatible; 6397 } 6398 6399 return Incompatible; 6400 } 6401 6402 // Conversions from pointers that are not covered by the above. 6403 if (isa<PointerType>(RHSType)) { 6404 // T* -> _Bool 6405 if (LHSType == Context.BoolTy) { 6406 Kind = CK_PointerToBoolean; 6407 return Compatible; 6408 } 6409 6410 // T* -> int 6411 if (LHSType->isIntegerType()) { 6412 Kind = CK_PointerToIntegral; 6413 return PointerToInt; 6414 } 6415 6416 return Incompatible; 6417 } 6418 6419 // Conversions from Objective-C pointers that are not covered by the above. 6420 if (isa<ObjCObjectPointerType>(RHSType)) { 6421 // T* -> _Bool 6422 if (LHSType == Context.BoolTy) { 6423 Kind = CK_PointerToBoolean; 6424 return Compatible; 6425 } 6426 6427 // T* -> int 6428 if (LHSType->isIntegerType()) { 6429 Kind = CK_PointerToIntegral; 6430 return PointerToInt; 6431 } 6432 6433 return Incompatible; 6434 } 6435 6436 // struct A -> struct B 6437 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6438 if (Context.typesAreCompatible(LHSType, RHSType)) { 6439 Kind = CK_NoOp; 6440 return Compatible; 6441 } 6442 } 6443 6444 return Incompatible; 6445} 6446 6447/// \brief Constructs a transparent union from an expression that is 6448/// used to initialize the transparent union. 6449static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6450 ExprResult &EResult, QualType UnionType, 6451 FieldDecl *Field) { 6452 // Build an initializer list that designates the appropriate member 6453 // of the transparent union. 6454 Expr *E = EResult.take(); 6455 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6456 E, SourceLocation()); 6457 Initializer->setType(UnionType); 6458 Initializer->setInitializedFieldInUnion(Field); 6459 6460 // Build a compound literal constructing a value of the transparent 6461 // union type from this initializer list. 6462 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6463 EResult = S.Owned( 6464 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6465 VK_RValue, Initializer, false)); 6466} 6467 6468Sema::AssignConvertType 6469Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6470 ExprResult &RHS) { 6471 QualType RHSType = RHS.get()->getType(); 6472 6473 // If the ArgType is a Union type, we want to handle a potential 6474 // transparent_union GCC extension. 6475 const RecordType *UT = ArgType->getAsUnionType(); 6476 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6477 return Incompatible; 6478 6479 // The field to initialize within the transparent union. 6480 RecordDecl *UD = UT->getDecl(); 6481 FieldDecl *InitField = 0; 6482 // It's compatible if the expression matches any of the fields. 6483 for (RecordDecl::field_iterator it = UD->field_begin(), 6484 itend = UD->field_end(); 6485 it != itend; ++it) { 6486 if (it->getType()->isPointerType()) { 6487 // If the transparent union contains a pointer type, we allow: 6488 // 1) void pointer 6489 // 2) null pointer constant 6490 if (RHSType->isPointerType()) 6491 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6492 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6493 InitField = *it; 6494 break; 6495 } 6496 6497 if (RHS.get()->isNullPointerConstant(Context, 6498 Expr::NPC_ValueDependentIsNull)) { 6499 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6500 CK_NullToPointer); 6501 InitField = *it; 6502 break; 6503 } 6504 } 6505 6506 CastKind Kind = CK_Invalid; 6507 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6508 == Compatible) { 6509 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6510 InitField = *it; 6511 break; 6512 } 6513 } 6514 6515 if (!InitField) 6516 return Incompatible; 6517 6518 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6519 return Compatible; 6520} 6521 6522Sema::AssignConvertType 6523Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6524 bool Diagnose, 6525 bool DiagnoseCFAudited) { 6526 if (getLangOpts().CPlusPlus) { 6527 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6528 // C++ 5.17p3: If the left operand is not of class type, the 6529 // expression is implicitly converted (C++ 4) to the 6530 // cv-unqualified type of the left operand. 6531 ExprResult Res; 6532 if (Diagnose) { 6533 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6534 AA_Assigning); 6535 } else { 6536 ImplicitConversionSequence ICS = 6537 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6538 /*SuppressUserConversions=*/false, 6539 /*AllowExplicit=*/false, 6540 /*InOverloadResolution=*/false, 6541 /*CStyle=*/false, 6542 /*AllowObjCWritebackConversion=*/false); 6543 if (ICS.isFailure()) 6544 return Incompatible; 6545 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6546 ICS, AA_Assigning); 6547 } 6548 if (Res.isInvalid()) 6549 return Incompatible; 6550 Sema::AssignConvertType result = Compatible; 6551 if (getLangOpts().ObjCAutoRefCount && 6552 !CheckObjCARCUnavailableWeakConversion(LHSType, 6553 RHS.get()->getType())) 6554 result = IncompatibleObjCWeakRef; 6555 RHS = Res; 6556 return result; 6557 } 6558 6559 // FIXME: Currently, we fall through and treat C++ classes like C 6560 // structures. 6561 // FIXME: We also fall through for atomics; not sure what should 6562 // happen there, though. 6563 } 6564 6565 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6566 // a null pointer constant. 6567 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6568 LHSType->isBlockPointerType()) && 6569 RHS.get()->isNullPointerConstant(Context, 6570 Expr::NPC_ValueDependentIsNull)) { 6571 CastKind Kind; 6572 CXXCastPath Path; 6573 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6574 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path); 6575 return Compatible; 6576 } 6577 6578 // This check seems unnatural, however it is necessary to ensure the proper 6579 // conversion of functions/arrays. If the conversion were done for all 6580 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6581 // expressions that suppress this implicit conversion (&, sizeof). 6582 // 6583 // Suppress this for references: C++ 8.5.3p5. 6584 if (!LHSType->isReferenceType()) { 6585 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6586 if (RHS.isInvalid()) 6587 return Incompatible; 6588 } 6589 6590 CastKind Kind = CK_Invalid; 6591 Sema::AssignConvertType result = 6592 CheckAssignmentConstraints(LHSType, RHS, Kind); 6593 6594 // C99 6.5.16.1p2: The value of the right operand is converted to the 6595 // type of the assignment expression. 6596 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6597 // so that we can use references in built-in functions even in C. 6598 // The getNonReferenceType() call makes sure that the resulting expression 6599 // does not have reference type. 6600 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6601 QualType Ty = LHSType.getNonLValueExprType(Context); 6602 Expr *E = RHS.take(); 6603 if (getLangOpts().ObjCAutoRefCount) 6604 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6605 DiagnoseCFAudited); 6606 RHS = ImpCastExprToType(E, Ty, Kind); 6607 } 6608 return result; 6609} 6610 6611QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6612 ExprResult &RHS) { 6613 Diag(Loc, diag::err_typecheck_invalid_operands) 6614 << LHS.get()->getType() << RHS.get()->getType() 6615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6616 return QualType(); 6617} 6618 6619QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6620 SourceLocation Loc, bool IsCompAssign) { 6621 if (!IsCompAssign) { 6622 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6623 if (LHS.isInvalid()) 6624 return QualType(); 6625 } 6626 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6627 if (RHS.isInvalid()) 6628 return QualType(); 6629 6630 // For conversion purposes, we ignore any qualifiers. 6631 // For example, "const float" and "float" are equivalent. 6632 QualType LHSType = 6633 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6634 QualType RHSType = 6635 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6636 6637 // If the vector types are identical, return. 6638 if (LHSType == RHSType) 6639 return LHSType; 6640 6641 // Handle the case of equivalent AltiVec and GCC vector types 6642 if (LHSType->isVectorType() && RHSType->isVectorType() && 6643 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6644 if (LHSType->isExtVectorType()) { 6645 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6646 return LHSType; 6647 } 6648 6649 if (!IsCompAssign) 6650 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6651 return RHSType; 6652 } 6653 6654 if (getLangOpts().LaxVectorConversions && 6655 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6656 // If we are allowing lax vector conversions, and LHS and RHS are both 6657 // vectors, the total size only needs to be the same. This is a 6658 // bitcast; no bits are changed but the result type is different. 6659 // FIXME: Should we really be allowing this? 6660 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6661 return LHSType; 6662 } 6663 6664 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6665 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6666 bool swapped = false; 6667 if (RHSType->isExtVectorType() && !IsCompAssign) { 6668 swapped = true; 6669 std::swap(RHS, LHS); 6670 std::swap(RHSType, LHSType); 6671 } 6672 6673 // Handle the case of an ext vector and scalar. 6674 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6675 QualType EltTy = LV->getElementType(); 6676 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6677 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6678 if (order > 0) 6679 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6680 if (order >= 0) { 6681 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6682 if (swapped) std::swap(RHS, LHS); 6683 return LHSType; 6684 } 6685 } 6686 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) { 6687 if (RHSType->isRealFloatingType()) { 6688 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6689 if (order > 0) 6690 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6691 if (order >= 0) { 6692 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6693 if (swapped) std::swap(RHS, LHS); 6694 return LHSType; 6695 } 6696 } 6697 if (RHSType->isIntegralType(Context)) { 6698 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating); 6699 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6700 if (swapped) std::swap(RHS, LHS); 6701 return LHSType; 6702 } 6703 } 6704 } 6705 6706 // Vectors of different size or scalar and non-ext-vector are errors. 6707 if (swapped) std::swap(RHS, LHS); 6708 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6709 << LHS.get()->getType() << RHS.get()->getType() 6710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6711 return QualType(); 6712} 6713 6714// checkArithmeticNull - Detect when a NULL constant is used improperly in an 6715// expression. These are mainly cases where the null pointer is used as an 6716// integer instead of a pointer. 6717static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6718 SourceLocation Loc, bool IsCompare) { 6719 // The canonical way to check for a GNU null is with isNullPointerConstant, 6720 // but we use a bit of a hack here for speed; this is a relatively 6721 // hot path, and isNullPointerConstant is slow. 6722 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6723 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6724 6725 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6726 6727 // Avoid analyzing cases where the result will either be invalid (and 6728 // diagnosed as such) or entirely valid and not something to warn about. 6729 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6730 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6731 return; 6732 6733 // Comparison operations would not make sense with a null pointer no matter 6734 // what the other expression is. 6735 if (!IsCompare) { 6736 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6737 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6738 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6739 return; 6740 } 6741 6742 // The rest of the operations only make sense with a null pointer 6743 // if the other expression is a pointer. 6744 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6745 NonNullType->canDecayToPointerType()) 6746 return; 6747 6748 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6749 << LHSNull /* LHS is NULL */ << NonNullType 6750 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6751} 6752 6753QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6754 SourceLocation Loc, 6755 bool IsCompAssign, bool IsDiv) { 6756 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6757 6758 if (LHS.get()->getType()->isVectorType() || 6759 RHS.get()->getType()->isVectorType()) 6760 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6761 6762 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6763 if (LHS.isInvalid() || RHS.isInvalid()) 6764 return QualType(); 6765 6766 6767 if (compType.isNull() || !compType->isArithmeticType()) 6768 return InvalidOperands(Loc, LHS, RHS); 6769 6770 // Check for division by zero. 6771 llvm::APSInt RHSValue; 6772 if (IsDiv && !RHS.get()->isValueDependent() && 6773 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6774 DiagRuntimeBehavior(Loc, RHS.get(), 6775 PDiag(diag::warn_division_by_zero) 6776 << RHS.get()->getSourceRange()); 6777 6778 return compType; 6779} 6780 6781QualType Sema::CheckRemainderOperands( 6782 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6783 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6784 6785 if (LHS.get()->getType()->isVectorType() || 6786 RHS.get()->getType()->isVectorType()) { 6787 if (LHS.get()->getType()->hasIntegerRepresentation() && 6788 RHS.get()->getType()->hasIntegerRepresentation()) 6789 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6790 return InvalidOperands(Loc, LHS, RHS); 6791 } 6792 6793 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6794 if (LHS.isInvalid() || RHS.isInvalid()) 6795 return QualType(); 6796 6797 if (compType.isNull() || !compType->isIntegerType()) 6798 return InvalidOperands(Loc, LHS, RHS); 6799 6800 // Check for remainder by zero. 6801 llvm::APSInt RHSValue; 6802 if (!RHS.get()->isValueDependent() && 6803 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6804 DiagRuntimeBehavior(Loc, RHS.get(), 6805 PDiag(diag::warn_remainder_by_zero) 6806 << RHS.get()->getSourceRange()); 6807 6808 return compType; 6809} 6810 6811/// \brief Diagnose invalid arithmetic on two void pointers. 6812static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6813 Expr *LHSExpr, Expr *RHSExpr) { 6814 S.Diag(Loc, S.getLangOpts().CPlusPlus 6815 ? diag::err_typecheck_pointer_arith_void_type 6816 : diag::ext_gnu_void_ptr) 6817 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6818 << RHSExpr->getSourceRange(); 6819} 6820 6821/// \brief Diagnose invalid arithmetic on a void pointer. 6822static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6823 Expr *Pointer) { 6824 S.Diag(Loc, S.getLangOpts().CPlusPlus 6825 ? diag::err_typecheck_pointer_arith_void_type 6826 : diag::ext_gnu_void_ptr) 6827 << 0 /* one pointer */ << Pointer->getSourceRange(); 6828} 6829 6830/// \brief Diagnose invalid arithmetic on two function pointers. 6831static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6832 Expr *LHS, Expr *RHS) { 6833 assert(LHS->getType()->isAnyPointerType()); 6834 assert(RHS->getType()->isAnyPointerType()); 6835 S.Diag(Loc, S.getLangOpts().CPlusPlus 6836 ? diag::err_typecheck_pointer_arith_function_type 6837 : diag::ext_gnu_ptr_func_arith) 6838 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6839 // We only show the second type if it differs from the first. 6840 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6841 RHS->getType()) 6842 << RHS->getType()->getPointeeType() 6843 << LHS->getSourceRange() << RHS->getSourceRange(); 6844} 6845 6846/// \brief Diagnose invalid arithmetic on a function pointer. 6847static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6848 Expr *Pointer) { 6849 assert(Pointer->getType()->isAnyPointerType()); 6850 S.Diag(Loc, S.getLangOpts().CPlusPlus 6851 ? diag::err_typecheck_pointer_arith_function_type 6852 : diag::ext_gnu_ptr_func_arith) 6853 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6854 << 0 /* one pointer, so only one type */ 6855 << Pointer->getSourceRange(); 6856} 6857 6858/// \brief Emit error if Operand is incomplete pointer type 6859/// 6860/// \returns True if pointer has incomplete type 6861static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6862 Expr *Operand) { 6863 assert(Operand->getType()->isAnyPointerType() && 6864 !Operand->getType()->isDependentType()); 6865 QualType PointeeTy = Operand->getType()->getPointeeType(); 6866 return S.RequireCompleteType(Loc, PointeeTy, 6867 diag::err_typecheck_arithmetic_incomplete_type, 6868 PointeeTy, Operand->getSourceRange()); 6869} 6870 6871/// \brief Check the validity of an arithmetic pointer operand. 6872/// 6873/// If the operand has pointer type, this code will check for pointer types 6874/// which are invalid in arithmetic operations. These will be diagnosed 6875/// appropriately, including whether or not the use is supported as an 6876/// extension. 6877/// 6878/// \returns True when the operand is valid to use (even if as an extension). 6879static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6880 Expr *Operand) { 6881 if (!Operand->getType()->isAnyPointerType()) return true; 6882 6883 QualType PointeeTy = Operand->getType()->getPointeeType(); 6884 if (PointeeTy->isVoidType()) { 6885 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6886 return !S.getLangOpts().CPlusPlus; 6887 } 6888 if (PointeeTy->isFunctionType()) { 6889 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6890 return !S.getLangOpts().CPlusPlus; 6891 } 6892 6893 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6894 6895 return true; 6896} 6897 6898/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6899/// operands. 6900/// 6901/// This routine will diagnose any invalid arithmetic on pointer operands much 6902/// like \see checkArithmeticOpPointerOperand. However, it has special logic 6903/// for emitting a single diagnostic even for operations where both LHS and RHS 6904/// are (potentially problematic) pointers. 6905/// 6906/// \returns True when the operand is valid to use (even if as an extension). 6907static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6908 Expr *LHSExpr, Expr *RHSExpr) { 6909 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6910 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6911 if (!isLHSPointer && !isRHSPointer) return true; 6912 6913 QualType LHSPointeeTy, RHSPointeeTy; 6914 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6915 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6916 6917 // Check for arithmetic on pointers to incomplete types. 6918 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6919 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6920 if (isLHSVoidPtr || isRHSVoidPtr) { 6921 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6922 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6923 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6924 6925 return !S.getLangOpts().CPlusPlus; 6926 } 6927 6928 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6929 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6930 if (isLHSFuncPtr || isRHSFuncPtr) { 6931 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6932 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6933 RHSExpr); 6934 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6935 6936 return !S.getLangOpts().CPlusPlus; 6937 } 6938 6939 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6940 return false; 6941 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6942 return false; 6943 6944 return true; 6945} 6946 6947/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6948/// literal. 6949static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6950 Expr *LHSExpr, Expr *RHSExpr) { 6951 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6952 Expr* IndexExpr = RHSExpr; 6953 if (!StrExpr) { 6954 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6955 IndexExpr = LHSExpr; 6956 } 6957 6958 bool IsStringPlusInt = StrExpr && 6959 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6960 if (!IsStringPlusInt) 6961 return; 6962 6963 llvm::APSInt index; 6964 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6965 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6966 if (index.isNonNegative() && 6967 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6968 index.isUnsigned())) 6969 return; 6970 } 6971 6972 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6973 Self.Diag(OpLoc, diag::warn_string_plus_int) 6974 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6975 6976 // Only print a fixit for "str" + int, not for int + "str". 6977 if (IndexExpr == RHSExpr) { 6978 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6979 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 6980 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6981 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6982 << FixItHint::CreateInsertion(EndLoc, "]"); 6983 } else 6984 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 6985} 6986 6987/// \brief Emit a warning when adding a char literal to a string. 6988static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 6989 Expr *LHSExpr, Expr *RHSExpr) { 6990 const DeclRefExpr *StringRefExpr = 6991 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 6992 const CharacterLiteral *CharExpr = 6993 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 6994 if (!StringRefExpr) { 6995 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 6996 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 6997 } 6998 6999 if (!CharExpr || !StringRefExpr) 7000 return; 7001 7002 const QualType StringType = StringRefExpr->getType(); 7003 7004 // Return if not a PointerType. 7005 if (!StringType->isAnyPointerType()) 7006 return; 7007 7008 // Return if not a CharacterType. 7009 if (!StringType->getPointeeType()->isAnyCharacterType()) 7010 return; 7011 7012 ASTContext &Ctx = Self.getASTContext(); 7013 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7014 7015 const QualType CharType = CharExpr->getType(); 7016 if (!CharType->isAnyCharacterType() && 7017 CharType->isIntegerType() && 7018 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7019 Self.Diag(OpLoc, diag::warn_string_plus_char) 7020 << DiagRange << Ctx.CharTy; 7021 } else { 7022 Self.Diag(OpLoc, diag::warn_string_plus_char) 7023 << DiagRange << CharExpr->getType(); 7024 } 7025 7026 // Only print a fixit for str + char, not for char + str. 7027 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7028 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7029 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7030 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7031 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7032 << FixItHint::CreateInsertion(EndLoc, "]"); 7033 } else { 7034 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7035 } 7036} 7037 7038/// \brief Emit error when two pointers are incompatible. 7039static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7040 Expr *LHSExpr, Expr *RHSExpr) { 7041 assert(LHSExpr->getType()->isAnyPointerType()); 7042 assert(RHSExpr->getType()->isAnyPointerType()); 7043 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7044 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7045 << RHSExpr->getSourceRange(); 7046} 7047 7048QualType Sema::CheckAdditionOperands( // C99 6.5.6 7049 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7050 QualType* CompLHSTy) { 7051 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7052 7053 if (LHS.get()->getType()->isVectorType() || 7054 RHS.get()->getType()->isVectorType()) { 7055 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7056 if (CompLHSTy) *CompLHSTy = compType; 7057 return compType; 7058 } 7059 7060 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7061 if (LHS.isInvalid() || RHS.isInvalid()) 7062 return QualType(); 7063 7064 // Diagnose "string literal" '+' int and string '+' "char literal". 7065 if (Opc == BO_Add) { 7066 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7067 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7068 } 7069 7070 // handle the common case first (both operands are arithmetic). 7071 if (!compType.isNull() && compType->isArithmeticType()) { 7072 if (CompLHSTy) *CompLHSTy = compType; 7073 return compType; 7074 } 7075 7076 // Type-checking. Ultimately the pointer's going to be in PExp; 7077 // note that we bias towards the LHS being the pointer. 7078 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7079 7080 bool isObjCPointer; 7081 if (PExp->getType()->isPointerType()) { 7082 isObjCPointer = false; 7083 } else if (PExp->getType()->isObjCObjectPointerType()) { 7084 isObjCPointer = true; 7085 } else { 7086 std::swap(PExp, IExp); 7087 if (PExp->getType()->isPointerType()) { 7088 isObjCPointer = false; 7089 } else if (PExp->getType()->isObjCObjectPointerType()) { 7090 isObjCPointer = true; 7091 } else { 7092 return InvalidOperands(Loc, LHS, RHS); 7093 } 7094 } 7095 assert(PExp->getType()->isAnyPointerType()); 7096 7097 if (!IExp->getType()->isIntegerType()) 7098 return InvalidOperands(Loc, LHS, RHS); 7099 7100 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7101 return QualType(); 7102 7103 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7104 return QualType(); 7105 7106 // Check array bounds for pointer arithemtic 7107 CheckArrayAccess(PExp, IExp); 7108 7109 if (CompLHSTy) { 7110 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7111 if (LHSTy.isNull()) { 7112 LHSTy = LHS.get()->getType(); 7113 if (LHSTy->isPromotableIntegerType()) 7114 LHSTy = Context.getPromotedIntegerType(LHSTy); 7115 } 7116 *CompLHSTy = LHSTy; 7117 } 7118 7119 return PExp->getType(); 7120} 7121 7122// C99 6.5.6 7123QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7124 SourceLocation Loc, 7125 QualType* CompLHSTy) { 7126 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7127 7128 if (LHS.get()->getType()->isVectorType() || 7129 RHS.get()->getType()->isVectorType()) { 7130 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7131 if (CompLHSTy) *CompLHSTy = compType; 7132 return compType; 7133 } 7134 7135 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7136 if (LHS.isInvalid() || RHS.isInvalid()) 7137 return QualType(); 7138 7139 // Enforce type constraints: C99 6.5.6p3. 7140 7141 // Handle the common case first (both operands are arithmetic). 7142 if (!compType.isNull() && compType->isArithmeticType()) { 7143 if (CompLHSTy) *CompLHSTy = compType; 7144 return compType; 7145 } 7146 7147 // Either ptr - int or ptr - ptr. 7148 if (LHS.get()->getType()->isAnyPointerType()) { 7149 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7150 7151 // Diagnose bad cases where we step over interface counts. 7152 if (LHS.get()->getType()->isObjCObjectPointerType() && 7153 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7154 return QualType(); 7155 7156 // The result type of a pointer-int computation is the pointer type. 7157 if (RHS.get()->getType()->isIntegerType()) { 7158 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7159 return QualType(); 7160 7161 // Check array bounds for pointer arithemtic 7162 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7163 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7164 7165 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7166 return LHS.get()->getType(); 7167 } 7168 7169 // Handle pointer-pointer subtractions. 7170 if (const PointerType *RHSPTy 7171 = RHS.get()->getType()->getAs<PointerType>()) { 7172 QualType rpointee = RHSPTy->getPointeeType(); 7173 7174 if (getLangOpts().CPlusPlus) { 7175 // Pointee types must be the same: C++ [expr.add] 7176 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7177 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7178 } 7179 } else { 7180 // Pointee types must be compatible C99 6.5.6p3 7181 if (!Context.typesAreCompatible( 7182 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7183 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7184 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7185 return QualType(); 7186 } 7187 } 7188 7189 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7190 LHS.get(), RHS.get())) 7191 return QualType(); 7192 7193 // The pointee type may have zero size. As an extension, a structure or 7194 // union may have zero size or an array may have zero length. In this 7195 // case subtraction does not make sense. 7196 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7197 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7198 if (ElementSize.isZero()) { 7199 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7200 << rpointee.getUnqualifiedType() 7201 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7202 } 7203 } 7204 7205 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7206 return Context.getPointerDiffType(); 7207 } 7208 } 7209 7210 return InvalidOperands(Loc, LHS, RHS); 7211} 7212 7213static bool isScopedEnumerationType(QualType T) { 7214 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7215 return ET->getDecl()->isScoped(); 7216 return false; 7217} 7218 7219static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7220 SourceLocation Loc, unsigned Opc, 7221 QualType LHSType) { 7222 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7223 // so skip remaining warnings as we don't want to modify values within Sema. 7224 if (S.getLangOpts().OpenCL) 7225 return; 7226 7227 llvm::APSInt Right; 7228 // Check right/shifter operand 7229 if (RHS.get()->isValueDependent() || 7230 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7231 return; 7232 7233 if (Right.isNegative()) { 7234 S.DiagRuntimeBehavior(Loc, RHS.get(), 7235 S.PDiag(diag::warn_shift_negative) 7236 << RHS.get()->getSourceRange()); 7237 return; 7238 } 7239 llvm::APInt LeftBits(Right.getBitWidth(), 7240 S.Context.getTypeSize(LHS.get()->getType())); 7241 if (Right.uge(LeftBits)) { 7242 S.DiagRuntimeBehavior(Loc, RHS.get(), 7243 S.PDiag(diag::warn_shift_gt_typewidth) 7244 << RHS.get()->getSourceRange()); 7245 return; 7246 } 7247 if (Opc != BO_Shl) 7248 return; 7249 7250 // When left shifting an ICE which is signed, we can check for overflow which 7251 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7252 // integers have defined behavior modulo one more than the maximum value 7253 // representable in the result type, so never warn for those. 7254 llvm::APSInt Left; 7255 if (LHS.get()->isValueDependent() || 7256 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7257 LHSType->hasUnsignedIntegerRepresentation()) 7258 return; 7259 llvm::APInt ResultBits = 7260 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7261 if (LeftBits.uge(ResultBits)) 7262 return; 7263 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7264 Result = Result.shl(Right); 7265 7266 // Print the bit representation of the signed integer as an unsigned 7267 // hexadecimal number. 7268 SmallString<40> HexResult; 7269 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7270 7271 // If we are only missing a sign bit, this is less likely to result in actual 7272 // bugs -- if the result is cast back to an unsigned type, it will have the 7273 // expected value. Thus we place this behind a different warning that can be 7274 // turned off separately if needed. 7275 if (LeftBits == ResultBits - 1) { 7276 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7277 << HexResult.str() << LHSType 7278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7279 return; 7280 } 7281 7282 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7283 << HexResult.str() << Result.getMinSignedBits() << LHSType 7284 << Left.getBitWidth() << LHS.get()->getSourceRange() 7285 << RHS.get()->getSourceRange(); 7286} 7287 7288// C99 6.5.7 7289QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7290 SourceLocation Loc, unsigned Opc, 7291 bool IsCompAssign) { 7292 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7293 7294 // Vector shifts promote their scalar inputs to vector type. 7295 if (LHS.get()->getType()->isVectorType() || 7296 RHS.get()->getType()->isVectorType()) 7297 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7298 7299 // Shifts don't perform usual arithmetic conversions, they just do integer 7300 // promotions on each operand. C99 6.5.7p3 7301 7302 // For the LHS, do usual unary conversions, but then reset them away 7303 // if this is a compound assignment. 7304 ExprResult OldLHS = LHS; 7305 LHS = UsualUnaryConversions(LHS.take()); 7306 if (LHS.isInvalid()) 7307 return QualType(); 7308 QualType LHSType = LHS.get()->getType(); 7309 if (IsCompAssign) LHS = OldLHS; 7310 7311 // The RHS is simpler. 7312 RHS = UsualUnaryConversions(RHS.take()); 7313 if (RHS.isInvalid()) 7314 return QualType(); 7315 QualType RHSType = RHS.get()->getType(); 7316 7317 // C99 6.5.7p2: Each of the operands shall have integer type. 7318 if (!LHSType->hasIntegerRepresentation() || 7319 !RHSType->hasIntegerRepresentation()) 7320 return InvalidOperands(Loc, LHS, RHS); 7321 7322 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7323 // hasIntegerRepresentation() above instead of this. 7324 if (isScopedEnumerationType(LHSType) || 7325 isScopedEnumerationType(RHSType)) { 7326 return InvalidOperands(Loc, LHS, RHS); 7327 } 7328 // Sanity-check shift operands 7329 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7330 7331 // "The type of the result is that of the promoted left operand." 7332 return LHSType; 7333} 7334 7335static bool IsWithinTemplateSpecialization(Decl *D) { 7336 if (DeclContext *DC = D->getDeclContext()) { 7337 if (isa<ClassTemplateSpecializationDecl>(DC)) 7338 return true; 7339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7340 return FD->isFunctionTemplateSpecialization(); 7341 } 7342 return false; 7343} 7344 7345/// If two different enums are compared, raise a warning. 7346static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7347 Expr *RHS) { 7348 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7349 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7350 7351 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7352 if (!LHSEnumType) 7353 return; 7354 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7355 if (!RHSEnumType) 7356 return; 7357 7358 // Ignore anonymous enums. 7359 if (!LHSEnumType->getDecl()->getIdentifier()) 7360 return; 7361 if (!RHSEnumType->getDecl()->getIdentifier()) 7362 return; 7363 7364 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7365 return; 7366 7367 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7368 << LHSStrippedType << RHSStrippedType 7369 << LHS->getSourceRange() << RHS->getSourceRange(); 7370} 7371 7372/// \brief Diagnose bad pointer comparisons. 7373static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7374 ExprResult &LHS, ExprResult &RHS, 7375 bool IsError) { 7376 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7377 : diag::ext_typecheck_comparison_of_distinct_pointers) 7378 << LHS.get()->getType() << RHS.get()->getType() 7379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7380} 7381 7382/// \brief Returns false if the pointers are converted to a composite type, 7383/// true otherwise. 7384static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7385 ExprResult &LHS, ExprResult &RHS) { 7386 // C++ [expr.rel]p2: 7387 // [...] Pointer conversions (4.10) and qualification 7388 // conversions (4.4) are performed on pointer operands (or on 7389 // a pointer operand and a null pointer constant) to bring 7390 // them to their composite pointer type. [...] 7391 // 7392 // C++ [expr.eq]p1 uses the same notion for (in)equality 7393 // comparisons of pointers. 7394 7395 // C++ [expr.eq]p2: 7396 // In addition, pointers to members can be compared, or a pointer to 7397 // member and a null pointer constant. Pointer to member conversions 7398 // (4.11) and qualification conversions (4.4) are performed to bring 7399 // them to a common type. If one operand is a null pointer constant, 7400 // the common type is the type of the other operand. Otherwise, the 7401 // common type is a pointer to member type similar (4.4) to the type 7402 // of one of the operands, with a cv-qualification signature (4.4) 7403 // that is the union of the cv-qualification signatures of the operand 7404 // types. 7405 7406 QualType LHSType = LHS.get()->getType(); 7407 QualType RHSType = RHS.get()->getType(); 7408 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7409 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7410 7411 bool NonStandardCompositeType = false; 7412 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7413 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7414 if (T.isNull()) { 7415 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7416 return true; 7417 } 7418 7419 if (NonStandardCompositeType) 7420 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7421 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7422 << RHS.get()->getSourceRange(); 7423 7424 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7425 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7426 return false; 7427} 7428 7429static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7430 ExprResult &LHS, 7431 ExprResult &RHS, 7432 bool IsError) { 7433 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7434 : diag::ext_typecheck_comparison_of_fptr_to_void) 7435 << LHS.get()->getType() << RHS.get()->getType() 7436 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7437} 7438 7439static bool isObjCObjectLiteral(ExprResult &E) { 7440 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7441 case Stmt::ObjCArrayLiteralClass: 7442 case Stmt::ObjCDictionaryLiteralClass: 7443 case Stmt::ObjCStringLiteralClass: 7444 case Stmt::ObjCBoxedExprClass: 7445 return true; 7446 default: 7447 // Note that ObjCBoolLiteral is NOT an object literal! 7448 return false; 7449 } 7450} 7451 7452static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7453 const ObjCObjectPointerType *Type = 7454 LHS->getType()->getAs<ObjCObjectPointerType>(); 7455 7456 // If this is not actually an Objective-C object, bail out. 7457 if (!Type) 7458 return false; 7459 7460 // Get the LHS object's interface type. 7461 QualType InterfaceType = Type->getPointeeType(); 7462 if (const ObjCObjectType *iQFaceTy = 7463 InterfaceType->getAsObjCQualifiedInterfaceType()) 7464 InterfaceType = iQFaceTy->getBaseType(); 7465 7466 // If the RHS isn't an Objective-C object, bail out. 7467 if (!RHS->getType()->isObjCObjectPointerType()) 7468 return false; 7469 7470 // Try to find the -isEqual: method. 7471 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7472 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7473 InterfaceType, 7474 /*instance=*/true); 7475 if (!Method) { 7476 if (Type->isObjCIdType()) { 7477 // For 'id', just check the global pool. 7478 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7479 /*receiverId=*/true, 7480 /*warn=*/false); 7481 } else { 7482 // Check protocols. 7483 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7484 /*instance=*/true); 7485 } 7486 } 7487 7488 if (!Method) 7489 return false; 7490 7491 QualType T = Method->param_begin()[0]->getType(); 7492 if (!T->isObjCObjectPointerType()) 7493 return false; 7494 7495 QualType R = Method->getResultType(); 7496 if (!R->isScalarType()) 7497 return false; 7498 7499 return true; 7500} 7501 7502Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7503 FromE = FromE->IgnoreParenImpCasts(); 7504 switch (FromE->getStmtClass()) { 7505 default: 7506 break; 7507 case Stmt::ObjCStringLiteralClass: 7508 // "string literal" 7509 return LK_String; 7510 case Stmt::ObjCArrayLiteralClass: 7511 // "array literal" 7512 return LK_Array; 7513 case Stmt::ObjCDictionaryLiteralClass: 7514 // "dictionary literal" 7515 return LK_Dictionary; 7516 case Stmt::BlockExprClass: 7517 return LK_Block; 7518 case Stmt::ObjCBoxedExprClass: { 7519 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7520 switch (Inner->getStmtClass()) { 7521 case Stmt::IntegerLiteralClass: 7522 case Stmt::FloatingLiteralClass: 7523 case Stmt::CharacterLiteralClass: 7524 case Stmt::ObjCBoolLiteralExprClass: 7525 case Stmt::CXXBoolLiteralExprClass: 7526 // "numeric literal" 7527 return LK_Numeric; 7528 case Stmt::ImplicitCastExprClass: { 7529 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7530 // Boolean literals can be represented by implicit casts. 7531 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7532 return LK_Numeric; 7533 break; 7534 } 7535 default: 7536 break; 7537 } 7538 return LK_Boxed; 7539 } 7540 } 7541 return LK_None; 7542} 7543 7544static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7545 ExprResult &LHS, ExprResult &RHS, 7546 BinaryOperator::Opcode Opc){ 7547 Expr *Literal; 7548 Expr *Other; 7549 if (isObjCObjectLiteral(LHS)) { 7550 Literal = LHS.get(); 7551 Other = RHS.get(); 7552 } else { 7553 Literal = RHS.get(); 7554 Other = LHS.get(); 7555 } 7556 7557 // Don't warn on comparisons against nil. 7558 Other = Other->IgnoreParenCasts(); 7559 if (Other->isNullPointerConstant(S.getASTContext(), 7560 Expr::NPC_ValueDependentIsNotNull)) 7561 return; 7562 7563 // This should be kept in sync with warn_objc_literal_comparison. 7564 // LK_String should always be after the other literals, since it has its own 7565 // warning flag. 7566 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7567 assert(LiteralKind != Sema::LK_Block); 7568 if (LiteralKind == Sema::LK_None) { 7569 llvm_unreachable("Unknown Objective-C object literal kind"); 7570 } 7571 7572 if (LiteralKind == Sema::LK_String) 7573 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7574 << Literal->getSourceRange(); 7575 else 7576 S.Diag(Loc, diag::warn_objc_literal_comparison) 7577 << LiteralKind << Literal->getSourceRange(); 7578 7579 if (BinaryOperator::isEqualityOp(Opc) && 7580 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7581 SourceLocation Start = LHS.get()->getLocStart(); 7582 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7583 CharSourceRange OpRange = 7584 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7585 7586 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7587 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7588 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7589 << FixItHint::CreateInsertion(End, "]"); 7590 } 7591} 7592 7593static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7594 ExprResult &RHS, 7595 SourceLocation Loc, 7596 unsigned OpaqueOpc) { 7597 // This checking requires bools. 7598 if (!S.getLangOpts().Bool) return; 7599 7600 // Check that left hand side is !something. 7601 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7602 if (!UO || UO->getOpcode() != UO_LNot) return; 7603 7604 // Only check if the right hand side is non-bool arithmetic type. 7605 if (RHS.get()->getType()->isBooleanType()) return; 7606 7607 // Make sure that the something in !something is not bool. 7608 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7609 if (SubExpr->getType()->isBooleanType()) return; 7610 7611 // Emit warning. 7612 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7613 << Loc; 7614 7615 // First note suggest !(x < y) 7616 SourceLocation FirstOpen = SubExpr->getLocStart(); 7617 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7618 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7619 if (FirstClose.isInvalid()) 7620 FirstOpen = SourceLocation(); 7621 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7622 << FixItHint::CreateInsertion(FirstOpen, "(") 7623 << FixItHint::CreateInsertion(FirstClose, ")"); 7624 7625 // Second note suggests (!x) < y 7626 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7627 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7628 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7629 if (SecondClose.isInvalid()) 7630 SecondOpen = SourceLocation(); 7631 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7632 << FixItHint::CreateInsertion(SecondOpen, "(") 7633 << FixItHint::CreateInsertion(SecondClose, ")"); 7634} 7635 7636// Get the decl for a simple expression: a reference to a variable, 7637// an implicit C++ field reference, or an implicit ObjC ivar reference. 7638static ValueDecl *getCompareDecl(Expr *E) { 7639 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7640 return DR->getDecl(); 7641 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7642 if (Ivar->isFreeIvar()) 7643 return Ivar->getDecl(); 7644 } 7645 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7646 if (Mem->isImplicitAccess()) 7647 return Mem->getMemberDecl(); 7648 } 7649 return 0; 7650} 7651 7652// C99 6.5.8, C++ [expr.rel] 7653QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7654 SourceLocation Loc, unsigned OpaqueOpc, 7655 bool IsRelational) { 7656 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7657 7658 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7659 7660 // Handle vector comparisons separately. 7661 if (LHS.get()->getType()->isVectorType() || 7662 RHS.get()->getType()->isVectorType()) 7663 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7664 7665 QualType LHSType = LHS.get()->getType(); 7666 QualType RHSType = RHS.get()->getType(); 7667 7668 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7669 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7670 7671 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7672 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7673 7674 if (!LHSType->hasFloatingRepresentation() && 7675 !(LHSType->isBlockPointerType() && IsRelational) && 7676 !LHS.get()->getLocStart().isMacroID() && 7677 !RHS.get()->getLocStart().isMacroID() && 7678 ActiveTemplateInstantiations.empty()) { 7679 // For non-floating point types, check for self-comparisons of the form 7680 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7681 // often indicate logic errors in the program. 7682 // 7683 // NOTE: Don't warn about comparison expressions resulting from macro 7684 // expansion. Also don't warn about comparisons which are only self 7685 // comparisons within a template specialization. The warnings should catch 7686 // obvious cases in the definition of the template anyways. The idea is to 7687 // warn when the typed comparison operator will always evaluate to the same 7688 // result. 7689 ValueDecl *DL = getCompareDecl(LHSStripped); 7690 ValueDecl *DR = getCompareDecl(RHSStripped); 7691 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7692 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7693 << 0 // self- 7694 << (Opc == BO_EQ 7695 || Opc == BO_LE 7696 || Opc == BO_GE)); 7697 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7698 !DL->getType()->isReferenceType() && 7699 !DR->getType()->isReferenceType()) { 7700 // what is it always going to eval to? 7701 char always_evals_to; 7702 switch(Opc) { 7703 case BO_EQ: // e.g. array1 == array2 7704 always_evals_to = 0; // false 7705 break; 7706 case BO_NE: // e.g. array1 != array2 7707 always_evals_to = 1; // true 7708 break; 7709 default: 7710 // best we can say is 'a constant' 7711 always_evals_to = 2; // e.g. array1 <= array2 7712 break; 7713 } 7714 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7715 << 1 // array 7716 << always_evals_to); 7717 } 7718 7719 if (isa<CastExpr>(LHSStripped)) 7720 LHSStripped = LHSStripped->IgnoreParenCasts(); 7721 if (isa<CastExpr>(RHSStripped)) 7722 RHSStripped = RHSStripped->IgnoreParenCasts(); 7723 7724 // Warn about comparisons against a string constant (unless the other 7725 // operand is null), the user probably wants strcmp. 7726 Expr *literalString = 0; 7727 Expr *literalStringStripped = 0; 7728 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7729 !RHSStripped->isNullPointerConstant(Context, 7730 Expr::NPC_ValueDependentIsNull)) { 7731 literalString = LHS.get(); 7732 literalStringStripped = LHSStripped; 7733 } else if ((isa<StringLiteral>(RHSStripped) || 7734 isa<ObjCEncodeExpr>(RHSStripped)) && 7735 !LHSStripped->isNullPointerConstant(Context, 7736 Expr::NPC_ValueDependentIsNull)) { 7737 literalString = RHS.get(); 7738 literalStringStripped = RHSStripped; 7739 } 7740 7741 if (literalString) { 7742 DiagRuntimeBehavior(Loc, 0, 7743 PDiag(diag::warn_stringcompare) 7744 << isa<ObjCEncodeExpr>(literalStringStripped) 7745 << literalString->getSourceRange()); 7746 } 7747 } 7748 7749 // C99 6.5.8p3 / C99 6.5.9p4 7750 UsualArithmeticConversions(LHS, RHS); 7751 if (LHS.isInvalid() || RHS.isInvalid()) 7752 return QualType(); 7753 7754 LHSType = LHS.get()->getType(); 7755 RHSType = RHS.get()->getType(); 7756 7757 // The result of comparisons is 'bool' in C++, 'int' in C. 7758 QualType ResultTy = Context.getLogicalOperationType(); 7759 7760 if (IsRelational) { 7761 if (LHSType->isRealType() && RHSType->isRealType()) 7762 return ResultTy; 7763 } else { 7764 // Check for comparisons of floating point operands using != and ==. 7765 if (LHSType->hasFloatingRepresentation()) 7766 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7767 7768 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7769 return ResultTy; 7770 } 7771 7772 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7773 Expr::NPC_ValueDependentIsNull); 7774 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7775 Expr::NPC_ValueDependentIsNull); 7776 7777 // All of the following pointer-related warnings are GCC extensions, except 7778 // when handling null pointer constants. 7779 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7780 QualType LCanPointeeTy = 7781 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7782 QualType RCanPointeeTy = 7783 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7784 7785 if (getLangOpts().CPlusPlus) { 7786 if (LCanPointeeTy == RCanPointeeTy) 7787 return ResultTy; 7788 if (!IsRelational && 7789 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7790 // Valid unless comparison between non-null pointer and function pointer 7791 // This is a gcc extension compatibility comparison. 7792 // In a SFINAE context, we treat this as a hard error to maintain 7793 // conformance with the C++ standard. 7794 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7795 && !LHSIsNull && !RHSIsNull) { 7796 diagnoseFunctionPointerToVoidComparison( 7797 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7798 7799 if (isSFINAEContext()) 7800 return QualType(); 7801 7802 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7803 return ResultTy; 7804 } 7805 } 7806 7807 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7808 return QualType(); 7809 else 7810 return ResultTy; 7811 } 7812 // C99 6.5.9p2 and C99 6.5.8p2 7813 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7814 RCanPointeeTy.getUnqualifiedType())) { 7815 // Valid unless a relational comparison of function pointers 7816 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7817 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7818 << LHSType << RHSType << LHS.get()->getSourceRange() 7819 << RHS.get()->getSourceRange(); 7820 } 7821 } else if (!IsRelational && 7822 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7823 // Valid unless comparison between non-null pointer and function pointer 7824 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7825 && !LHSIsNull && !RHSIsNull) 7826 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7827 /*isError*/false); 7828 } else { 7829 // Invalid 7830 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7831 } 7832 if (LCanPointeeTy != RCanPointeeTy) { 7833 if (LHSIsNull && !RHSIsNull) 7834 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7835 else 7836 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7837 } 7838 return ResultTy; 7839 } 7840 7841 if (getLangOpts().CPlusPlus) { 7842 // Comparison of nullptr_t with itself. 7843 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7844 return ResultTy; 7845 7846 // Comparison of pointers with null pointer constants and equality 7847 // comparisons of member pointers to null pointer constants. 7848 if (RHSIsNull && 7849 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7850 (!IsRelational && 7851 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7852 RHS = ImpCastExprToType(RHS.take(), LHSType, 7853 LHSType->isMemberPointerType() 7854 ? CK_NullToMemberPointer 7855 : CK_NullToPointer); 7856 return ResultTy; 7857 } 7858 if (LHSIsNull && 7859 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7860 (!IsRelational && 7861 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7862 LHS = ImpCastExprToType(LHS.take(), RHSType, 7863 RHSType->isMemberPointerType() 7864 ? CK_NullToMemberPointer 7865 : CK_NullToPointer); 7866 return ResultTy; 7867 } 7868 7869 // Comparison of member pointers. 7870 if (!IsRelational && 7871 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7872 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7873 return QualType(); 7874 else 7875 return ResultTy; 7876 } 7877 7878 // Handle scoped enumeration types specifically, since they don't promote 7879 // to integers. 7880 if (LHS.get()->getType()->isEnumeralType() && 7881 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7882 RHS.get()->getType())) 7883 return ResultTy; 7884 } 7885 7886 // Handle block pointer types. 7887 if (!IsRelational && LHSType->isBlockPointerType() && 7888 RHSType->isBlockPointerType()) { 7889 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7890 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7891 7892 if (!LHSIsNull && !RHSIsNull && 7893 !Context.typesAreCompatible(lpointee, rpointee)) { 7894 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7895 << LHSType << RHSType << LHS.get()->getSourceRange() 7896 << RHS.get()->getSourceRange(); 7897 } 7898 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7899 return ResultTy; 7900 } 7901 7902 // Allow block pointers to be compared with null pointer constants. 7903 if (!IsRelational 7904 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7905 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7906 if (!LHSIsNull && !RHSIsNull) { 7907 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7908 ->getPointeeType()->isVoidType()) 7909 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7910 ->getPointeeType()->isVoidType()))) 7911 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7912 << LHSType << RHSType << LHS.get()->getSourceRange() 7913 << RHS.get()->getSourceRange(); 7914 } 7915 if (LHSIsNull && !RHSIsNull) 7916 LHS = ImpCastExprToType(LHS.take(), RHSType, 7917 RHSType->isPointerType() ? CK_BitCast 7918 : CK_AnyPointerToBlockPointerCast); 7919 else 7920 RHS = ImpCastExprToType(RHS.take(), LHSType, 7921 LHSType->isPointerType() ? CK_BitCast 7922 : CK_AnyPointerToBlockPointerCast); 7923 return ResultTy; 7924 } 7925 7926 if (LHSType->isObjCObjectPointerType() || 7927 RHSType->isObjCObjectPointerType()) { 7928 const PointerType *LPT = LHSType->getAs<PointerType>(); 7929 const PointerType *RPT = RHSType->getAs<PointerType>(); 7930 if (LPT || RPT) { 7931 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7932 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7933 7934 if (!LPtrToVoid && !RPtrToVoid && 7935 !Context.typesAreCompatible(LHSType, RHSType)) { 7936 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7937 /*isError*/false); 7938 } 7939 if (LHSIsNull && !RHSIsNull) { 7940 Expr *E = LHS.take(); 7941 if (getLangOpts().ObjCAutoRefCount) 7942 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 7943 LHS = ImpCastExprToType(E, RHSType, 7944 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7945 } 7946 else { 7947 Expr *E = RHS.take(); 7948 if (getLangOpts().ObjCAutoRefCount) 7949 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 7950 RHS = ImpCastExprToType(E, LHSType, 7951 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7952 } 7953 return ResultTy; 7954 } 7955 if (LHSType->isObjCObjectPointerType() && 7956 RHSType->isObjCObjectPointerType()) { 7957 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7958 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7959 /*isError*/false); 7960 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7961 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7962 7963 if (LHSIsNull && !RHSIsNull) 7964 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7965 else 7966 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7967 return ResultTy; 7968 } 7969 } 7970 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7971 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7972 unsigned DiagID = 0; 7973 bool isError = false; 7974 if (LangOpts.DebuggerSupport) { 7975 // Under a debugger, allow the comparison of pointers to integers, 7976 // since users tend to want to compare addresses. 7977 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7978 (RHSIsNull && RHSType->isIntegerType())) { 7979 if (IsRelational && !getLangOpts().CPlusPlus) 7980 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7981 } else if (IsRelational && !getLangOpts().CPlusPlus) 7982 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7983 else if (getLangOpts().CPlusPlus) { 7984 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7985 isError = true; 7986 } else 7987 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7988 7989 if (DiagID) { 7990 Diag(Loc, DiagID) 7991 << LHSType << RHSType << LHS.get()->getSourceRange() 7992 << RHS.get()->getSourceRange(); 7993 if (isError) 7994 return QualType(); 7995 } 7996 7997 if (LHSType->isIntegerType()) 7998 LHS = ImpCastExprToType(LHS.take(), RHSType, 7999 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8000 else 8001 RHS = ImpCastExprToType(RHS.take(), LHSType, 8002 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8003 return ResultTy; 8004 } 8005 8006 // Handle block pointers. 8007 if (!IsRelational && RHSIsNull 8008 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8009 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8010 return ResultTy; 8011 } 8012 if (!IsRelational && LHSIsNull 8013 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8014 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8015 return ResultTy; 8016 } 8017 8018 return InvalidOperands(Loc, LHS, RHS); 8019} 8020 8021 8022// Return a signed type that is of identical size and number of elements. 8023// For floating point vectors, return an integer type of identical size 8024// and number of elements. 8025QualType Sema::GetSignedVectorType(QualType V) { 8026 const VectorType *VTy = V->getAs<VectorType>(); 8027 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8028 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8029 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8030 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8031 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8032 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8033 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8034 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8035 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8036 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8037 "Unhandled vector element size in vector compare"); 8038 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8039} 8040 8041/// CheckVectorCompareOperands - vector comparisons are a clang extension that 8042/// operates on extended vector types. Instead of producing an IntTy result, 8043/// like a scalar comparison, a vector comparison produces a vector of integer 8044/// types. 8045QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8046 SourceLocation Loc, 8047 bool IsRelational) { 8048 // Check to make sure we're operating on vectors of the same type and width, 8049 // Allowing one side to be a scalar of element type. 8050 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8051 if (vType.isNull()) 8052 return vType; 8053 8054 QualType LHSType = LHS.get()->getType(); 8055 8056 // If AltiVec, the comparison results in a numeric type, i.e. 8057 // bool for C++, int for C 8058 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8059 return Context.getLogicalOperationType(); 8060 8061 // For non-floating point types, check for self-comparisons of the form 8062 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8063 // often indicate logic errors in the program. 8064 if (!LHSType->hasFloatingRepresentation() && 8065 ActiveTemplateInstantiations.empty()) { 8066 if (DeclRefExpr* DRL 8067 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8068 if (DeclRefExpr* DRR 8069 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8070 if (DRL->getDecl() == DRR->getDecl()) 8071 DiagRuntimeBehavior(Loc, 0, 8072 PDiag(diag::warn_comparison_always) 8073 << 0 // self- 8074 << 2 // "a constant" 8075 ); 8076 } 8077 8078 // Check for comparisons of floating point operands using != and ==. 8079 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8080 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8081 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8082 } 8083 8084 // Return a signed type for the vector. 8085 return GetSignedVectorType(LHSType); 8086} 8087 8088QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8089 SourceLocation Loc) { 8090 // Ensure that either both operands are of the same vector type, or 8091 // one operand is of a vector type and the other is of its element type. 8092 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8093 if (vType.isNull()) 8094 return InvalidOperands(Loc, LHS, RHS); 8095 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8096 vType->hasFloatingRepresentation()) 8097 return InvalidOperands(Loc, LHS, RHS); 8098 8099 return GetSignedVectorType(LHS.get()->getType()); 8100} 8101 8102inline QualType Sema::CheckBitwiseOperands( 8103 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8104 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8105 8106 if (LHS.get()->getType()->isVectorType() || 8107 RHS.get()->getType()->isVectorType()) { 8108 if (LHS.get()->getType()->hasIntegerRepresentation() && 8109 RHS.get()->getType()->hasIntegerRepresentation()) 8110 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8111 8112 return InvalidOperands(Loc, LHS, RHS); 8113 } 8114 8115 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8116 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8117 IsCompAssign); 8118 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8119 return QualType(); 8120 LHS = LHSResult.take(); 8121 RHS = RHSResult.take(); 8122 8123 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8124 return compType; 8125 return InvalidOperands(Loc, LHS, RHS); 8126} 8127 8128inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8129 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8130 8131 // Check vector operands differently. 8132 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8133 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8134 8135 // Diagnose cases where the user write a logical and/or but probably meant a 8136 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8137 // is a constant. 8138 if (LHS.get()->getType()->isIntegerType() && 8139 !LHS.get()->getType()->isBooleanType() && 8140 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8141 // Don't warn in macros or template instantiations. 8142 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8143 // If the RHS can be constant folded, and if it constant folds to something 8144 // that isn't 0 or 1 (which indicate a potential logical operation that 8145 // happened to fold to true/false) then warn. 8146 // Parens on the RHS are ignored. 8147 llvm::APSInt Result; 8148 if (RHS.get()->EvaluateAsInt(Result, Context)) 8149 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8150 (Result != 0 && Result != 1)) { 8151 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8152 << RHS.get()->getSourceRange() 8153 << (Opc == BO_LAnd ? "&&" : "||"); 8154 // Suggest replacing the logical operator with the bitwise version 8155 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8156 << (Opc == BO_LAnd ? "&" : "|") 8157 << FixItHint::CreateReplacement(SourceRange( 8158 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8159 getLangOpts())), 8160 Opc == BO_LAnd ? "&" : "|"); 8161 if (Opc == BO_LAnd) 8162 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8163 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8164 << FixItHint::CreateRemoval( 8165 SourceRange( 8166 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8167 0, getSourceManager(), 8168 getLangOpts()), 8169 RHS.get()->getLocEnd())); 8170 } 8171 } 8172 8173 if (!Context.getLangOpts().CPlusPlus) { 8174 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8175 // not operate on the built-in scalar and vector float types. 8176 if (Context.getLangOpts().OpenCL && 8177 Context.getLangOpts().OpenCLVersion < 120) { 8178 if (LHS.get()->getType()->isFloatingType() || 8179 RHS.get()->getType()->isFloatingType()) 8180 return InvalidOperands(Loc, LHS, RHS); 8181 } 8182 8183 LHS = UsualUnaryConversions(LHS.take()); 8184 if (LHS.isInvalid()) 8185 return QualType(); 8186 8187 RHS = UsualUnaryConversions(RHS.take()); 8188 if (RHS.isInvalid()) 8189 return QualType(); 8190 8191 if (!LHS.get()->getType()->isScalarType() || 8192 !RHS.get()->getType()->isScalarType()) 8193 return InvalidOperands(Loc, LHS, RHS); 8194 8195 return Context.IntTy; 8196 } 8197 8198 // The following is safe because we only use this method for 8199 // non-overloadable operands. 8200 8201 // C++ [expr.log.and]p1 8202 // C++ [expr.log.or]p1 8203 // The operands are both contextually converted to type bool. 8204 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8205 if (LHSRes.isInvalid()) 8206 return InvalidOperands(Loc, LHS, RHS); 8207 LHS = LHSRes; 8208 8209 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8210 if (RHSRes.isInvalid()) 8211 return InvalidOperands(Loc, LHS, RHS); 8212 RHS = RHSRes; 8213 8214 // C++ [expr.log.and]p2 8215 // C++ [expr.log.or]p2 8216 // The result is a bool. 8217 return Context.BoolTy; 8218} 8219 8220static bool IsReadonlyMessage(Expr *E, Sema &S) { 8221 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8222 if (!ME) return false; 8223 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8224 ObjCMessageExpr *Base = 8225 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8226 if (!Base) return false; 8227 return Base->getMethodDecl() != 0; 8228} 8229 8230/// Is the given expression (which must be 'const') a reference to a 8231/// variable which was originally non-const, but which has become 8232/// 'const' due to being captured within a block? 8233enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8234static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8235 assert(E->isLValue() && E->getType().isConstQualified()); 8236 E = E->IgnoreParens(); 8237 8238 // Must be a reference to a declaration from an enclosing scope. 8239 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8240 if (!DRE) return NCCK_None; 8241 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8242 8243 // The declaration must be a variable which is not declared 'const'. 8244 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8245 if (!var) return NCCK_None; 8246 if (var->getType().isConstQualified()) return NCCK_None; 8247 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8248 8249 // Decide whether the first capture was for a block or a lambda. 8250 DeclContext *DC = S.CurContext, *Prev = 0; 8251 while (DC != var->getDeclContext()) { 8252 Prev = DC; 8253 DC = DC->getParent(); 8254 } 8255 // Unless we have an init-capture, we've gone one step too far. 8256 if (!var->isInitCapture()) 8257 DC = Prev; 8258 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8259} 8260 8261/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8262/// emit an error and return true. If so, return false. 8263static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8264 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8265 SourceLocation OrigLoc = Loc; 8266 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8267 &Loc); 8268 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8269 IsLV = Expr::MLV_InvalidMessageExpression; 8270 if (IsLV == Expr::MLV_Valid) 8271 return false; 8272 8273 unsigned Diag = 0; 8274 bool NeedType = false; 8275 switch (IsLV) { // C99 6.5.16p2 8276 case Expr::MLV_ConstQualified: 8277 Diag = diag::err_typecheck_assign_const; 8278 8279 // Use a specialized diagnostic when we're assigning to an object 8280 // from an enclosing function or block. 8281 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8282 if (NCCK == NCCK_Block) 8283 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8284 else 8285 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8286 break; 8287 } 8288 8289 // In ARC, use some specialized diagnostics for occasions where we 8290 // infer 'const'. These are always pseudo-strong variables. 8291 if (S.getLangOpts().ObjCAutoRefCount) { 8292 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8293 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8294 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8295 8296 // Use the normal diagnostic if it's pseudo-__strong but the 8297 // user actually wrote 'const'. 8298 if (var->isARCPseudoStrong() && 8299 (!var->getTypeSourceInfo() || 8300 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8301 // There are two pseudo-strong cases: 8302 // - self 8303 ObjCMethodDecl *method = S.getCurMethodDecl(); 8304 if (method && var == method->getSelfDecl()) 8305 Diag = method->isClassMethod() 8306 ? diag::err_typecheck_arc_assign_self_class_method 8307 : diag::err_typecheck_arc_assign_self; 8308 8309 // - fast enumeration variables 8310 else 8311 Diag = diag::err_typecheck_arr_assign_enumeration; 8312 8313 SourceRange Assign; 8314 if (Loc != OrigLoc) 8315 Assign = SourceRange(OrigLoc, OrigLoc); 8316 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8317 // We need to preserve the AST regardless, so migration tool 8318 // can do its job. 8319 return false; 8320 } 8321 } 8322 } 8323 8324 break; 8325 case Expr::MLV_ArrayType: 8326 case Expr::MLV_ArrayTemporary: 8327 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8328 NeedType = true; 8329 break; 8330 case Expr::MLV_NotObjectType: 8331 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8332 NeedType = true; 8333 break; 8334 case Expr::MLV_LValueCast: 8335 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8336 break; 8337 case Expr::MLV_Valid: 8338 llvm_unreachable("did not take early return for MLV_Valid"); 8339 case Expr::MLV_InvalidExpression: 8340 case Expr::MLV_MemberFunction: 8341 case Expr::MLV_ClassTemporary: 8342 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8343 break; 8344 case Expr::MLV_IncompleteType: 8345 case Expr::MLV_IncompleteVoidType: 8346 return S.RequireCompleteType(Loc, E->getType(), 8347 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8348 case Expr::MLV_DuplicateVectorComponents: 8349 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8350 break; 8351 case Expr::MLV_NoSetterProperty: 8352 llvm_unreachable("readonly properties should be processed differently"); 8353 case Expr::MLV_InvalidMessageExpression: 8354 Diag = diag::error_readonly_message_assignment; 8355 break; 8356 case Expr::MLV_SubObjCPropertySetting: 8357 Diag = diag::error_no_subobject_property_setting; 8358 break; 8359 } 8360 8361 SourceRange Assign; 8362 if (Loc != OrigLoc) 8363 Assign = SourceRange(OrigLoc, OrigLoc); 8364 if (NeedType) 8365 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8366 else 8367 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8368 return true; 8369} 8370 8371static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8372 SourceLocation Loc, 8373 Sema &Sema) { 8374 // C / C++ fields 8375 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8376 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8377 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8378 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8379 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8380 } 8381 8382 // Objective-C instance variables 8383 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8384 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8385 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8386 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8387 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8388 if (RL && RR && RL->getDecl() == RR->getDecl()) 8389 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8390 } 8391} 8392 8393// C99 6.5.16.1 8394QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8395 SourceLocation Loc, 8396 QualType CompoundType) { 8397 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8398 8399 // Verify that LHS is a modifiable lvalue, and emit error if not. 8400 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8401 return QualType(); 8402 8403 QualType LHSType = LHSExpr->getType(); 8404 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8405 CompoundType; 8406 AssignConvertType ConvTy; 8407 if (CompoundType.isNull()) { 8408 Expr *RHSCheck = RHS.get(); 8409 8410 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8411 8412 QualType LHSTy(LHSType); 8413 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8414 if (RHS.isInvalid()) 8415 return QualType(); 8416 // Special case of NSObject attributes on c-style pointer types. 8417 if (ConvTy == IncompatiblePointer && 8418 ((Context.isObjCNSObjectType(LHSType) && 8419 RHSType->isObjCObjectPointerType()) || 8420 (Context.isObjCNSObjectType(RHSType) && 8421 LHSType->isObjCObjectPointerType()))) 8422 ConvTy = Compatible; 8423 8424 if (ConvTy == Compatible && 8425 LHSType->isObjCObjectType()) 8426 Diag(Loc, diag::err_objc_object_assignment) 8427 << LHSType; 8428 8429 // If the RHS is a unary plus or minus, check to see if they = and + are 8430 // right next to each other. If so, the user may have typo'd "x =+ 4" 8431 // instead of "x += 4". 8432 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8433 RHSCheck = ICE->getSubExpr(); 8434 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8435 if ((UO->getOpcode() == UO_Plus || 8436 UO->getOpcode() == UO_Minus) && 8437 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8438 // Only if the two operators are exactly adjacent. 8439 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8440 // And there is a space or other character before the subexpr of the 8441 // unary +/-. We don't want to warn on "x=-1". 8442 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8443 UO->getSubExpr()->getLocStart().isFileID()) { 8444 Diag(Loc, diag::warn_not_compound_assign) 8445 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8446 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8447 } 8448 } 8449 8450 if (ConvTy == Compatible) { 8451 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8452 // Warn about retain cycles where a block captures the LHS, but 8453 // not if the LHS is a simple variable into which the block is 8454 // being stored...unless that variable can be captured by reference! 8455 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8456 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8457 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8458 checkRetainCycles(LHSExpr, RHS.get()); 8459 8460 // It is safe to assign a weak reference into a strong variable. 8461 // Although this code can still have problems: 8462 // id x = self.weakProp; 8463 // id y = self.weakProp; 8464 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8465 // paths through the function. This should be revisited if 8466 // -Wrepeated-use-of-weak is made flow-sensitive. 8467 DiagnosticsEngine::Level Level = 8468 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8469 RHS.get()->getLocStart()); 8470 if (Level != DiagnosticsEngine::Ignored) 8471 getCurFunction()->markSafeWeakUse(RHS.get()); 8472 8473 } else if (getLangOpts().ObjCAutoRefCount) { 8474 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8475 } 8476 } 8477 } else { 8478 // Compound assignment "x += y" 8479 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8480 } 8481 8482 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8483 RHS.get(), AA_Assigning)) 8484 return QualType(); 8485 8486 CheckForNullPointerDereference(*this, LHSExpr); 8487 8488 // C99 6.5.16p3: The type of an assignment expression is the type of the 8489 // left operand unless the left operand has qualified type, in which case 8490 // it is the unqualified version of the type of the left operand. 8491 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8492 // is converted to the type of the assignment expression (above). 8493 // C++ 5.17p1: the type of the assignment expression is that of its left 8494 // operand. 8495 return (getLangOpts().CPlusPlus 8496 ? LHSType : LHSType.getUnqualifiedType()); 8497} 8498 8499// C99 6.5.17 8500static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8501 SourceLocation Loc) { 8502 LHS = S.CheckPlaceholderExpr(LHS.take()); 8503 RHS = S.CheckPlaceholderExpr(RHS.take()); 8504 if (LHS.isInvalid() || RHS.isInvalid()) 8505 return QualType(); 8506 8507 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8508 // operands, but not unary promotions. 8509 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8510 8511 // So we treat the LHS as a ignored value, and in C++ we allow the 8512 // containing site to determine what should be done with the RHS. 8513 LHS = S.IgnoredValueConversions(LHS.take()); 8514 if (LHS.isInvalid()) 8515 return QualType(); 8516 8517 S.DiagnoseUnusedExprResult(LHS.get()); 8518 8519 if (!S.getLangOpts().CPlusPlus) { 8520 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8521 if (RHS.isInvalid()) 8522 return QualType(); 8523 if (!RHS.get()->getType()->isVoidType()) 8524 S.RequireCompleteType(Loc, RHS.get()->getType(), 8525 diag::err_incomplete_type); 8526 } 8527 8528 return RHS.get()->getType(); 8529} 8530 8531/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8532/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8533static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8534 ExprValueKind &VK, 8535 SourceLocation OpLoc, 8536 bool IsInc, bool IsPrefix) { 8537 if (Op->isTypeDependent()) 8538 return S.Context.DependentTy; 8539 8540 QualType ResType = Op->getType(); 8541 // Atomic types can be used for increment / decrement where the non-atomic 8542 // versions can, so ignore the _Atomic() specifier for the purpose of 8543 // checking. 8544 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8545 ResType = ResAtomicType->getValueType(); 8546 8547 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8548 8549 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8550 // Decrement of bool is not allowed. 8551 if (!IsInc) { 8552 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8553 return QualType(); 8554 } 8555 // Increment of bool sets it to true, but is deprecated. 8556 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8557 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8558 // Error on enum increments and decrements in C++ mode 8559 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8560 return QualType(); 8561 } else if (ResType->isRealType()) { 8562 // OK! 8563 } else if (ResType->isPointerType()) { 8564 // C99 6.5.2.4p2, 6.5.6p2 8565 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8566 return QualType(); 8567 } else if (ResType->isObjCObjectPointerType()) { 8568 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8569 // Otherwise, we just need a complete type. 8570 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8571 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8572 return QualType(); 8573 } else if (ResType->isAnyComplexType()) { 8574 // C99 does not support ++/-- on complex types, we allow as an extension. 8575 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8576 << ResType << Op->getSourceRange(); 8577 } else if (ResType->isPlaceholderType()) { 8578 ExprResult PR = S.CheckPlaceholderExpr(Op); 8579 if (PR.isInvalid()) return QualType(); 8580 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8581 IsInc, IsPrefix); 8582 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8583 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8584 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8585 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8586 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8587 } else { 8588 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8589 << ResType << int(IsInc) << Op->getSourceRange(); 8590 return QualType(); 8591 } 8592 // At this point, we know we have a real, complex or pointer type. 8593 // Now make sure the operand is a modifiable lvalue. 8594 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8595 return QualType(); 8596 // In C++, a prefix increment is the same type as the operand. Otherwise 8597 // (in C or with postfix), the increment is the unqualified type of the 8598 // operand. 8599 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8600 VK = VK_LValue; 8601 return ResType; 8602 } else { 8603 VK = VK_RValue; 8604 return ResType.getUnqualifiedType(); 8605 } 8606} 8607 8608 8609/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8610/// This routine allows us to typecheck complex/recursive expressions 8611/// where the declaration is needed for type checking. We only need to 8612/// handle cases when the expression references a function designator 8613/// or is an lvalue. Here are some examples: 8614/// - &(x) => x 8615/// - &*****f => f for f a function designator. 8616/// - &s.xx => s 8617/// - &s.zz[1].yy -> s, if zz is an array 8618/// - *(x + 1) -> x, if x is an array 8619/// - &"123"[2] -> 0 8620/// - & __real__ x -> x 8621static ValueDecl *getPrimaryDecl(Expr *E) { 8622 switch (E->getStmtClass()) { 8623 case Stmt::DeclRefExprClass: 8624 return cast<DeclRefExpr>(E)->getDecl(); 8625 case Stmt::MemberExprClass: 8626 // If this is an arrow operator, the address is an offset from 8627 // the base's value, so the object the base refers to is 8628 // irrelevant. 8629 if (cast<MemberExpr>(E)->isArrow()) 8630 return 0; 8631 // Otherwise, the expression refers to a part of the base 8632 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8633 case Stmt::ArraySubscriptExprClass: { 8634 // FIXME: This code shouldn't be necessary! We should catch the implicit 8635 // promotion of register arrays earlier. 8636 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8637 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8638 if (ICE->getSubExpr()->getType()->isArrayType()) 8639 return getPrimaryDecl(ICE->getSubExpr()); 8640 } 8641 return 0; 8642 } 8643 case Stmt::UnaryOperatorClass: { 8644 UnaryOperator *UO = cast<UnaryOperator>(E); 8645 8646 switch(UO->getOpcode()) { 8647 case UO_Real: 8648 case UO_Imag: 8649 case UO_Extension: 8650 return getPrimaryDecl(UO->getSubExpr()); 8651 default: 8652 return 0; 8653 } 8654 } 8655 case Stmt::ParenExprClass: 8656 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8657 case Stmt::ImplicitCastExprClass: 8658 // If the result of an implicit cast is an l-value, we care about 8659 // the sub-expression; otherwise, the result here doesn't matter. 8660 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8661 default: 8662 return 0; 8663 } 8664} 8665 8666namespace { 8667 enum { 8668 AO_Bit_Field = 0, 8669 AO_Vector_Element = 1, 8670 AO_Property_Expansion = 2, 8671 AO_Register_Variable = 3, 8672 AO_No_Error = 4 8673 }; 8674} 8675/// \brief Diagnose invalid operand for address of operations. 8676/// 8677/// \param Type The type of operand which cannot have its address taken. 8678static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8679 Expr *E, unsigned Type) { 8680 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8681} 8682 8683/// CheckAddressOfOperand - The operand of & must be either a function 8684/// designator or an lvalue designating an object. If it is an lvalue, the 8685/// object cannot be declared with storage class register or be a bit field. 8686/// Note: The usual conversions are *not* applied to the operand of the & 8687/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8688/// In C++, the operand might be an overloaded function name, in which case 8689/// we allow the '&' but retain the overloaded-function type. 8690QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8691 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8692 if (PTy->getKind() == BuiltinType::Overload) { 8693 Expr *E = OrigOp.get()->IgnoreParens(); 8694 if (!isa<OverloadExpr>(E)) { 8695 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8696 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8697 << OrigOp.get()->getSourceRange(); 8698 return QualType(); 8699 } 8700 8701 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8702 if (isa<UnresolvedMemberExpr>(Ovl)) 8703 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8704 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8705 << OrigOp.get()->getSourceRange(); 8706 return QualType(); 8707 } 8708 8709 return Context.OverloadTy; 8710 } 8711 8712 if (PTy->getKind() == BuiltinType::UnknownAny) 8713 return Context.UnknownAnyTy; 8714 8715 if (PTy->getKind() == BuiltinType::BoundMember) { 8716 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8717 << OrigOp.get()->getSourceRange(); 8718 return QualType(); 8719 } 8720 8721 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8722 if (OrigOp.isInvalid()) return QualType(); 8723 } 8724 8725 if (OrigOp.get()->isTypeDependent()) 8726 return Context.DependentTy; 8727 8728 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8729 8730 // Make sure to ignore parentheses in subsequent checks 8731 Expr *op = OrigOp.get()->IgnoreParens(); 8732 8733 if (getLangOpts().C99) { 8734 // Implement C99-only parts of addressof rules. 8735 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8736 if (uOp->getOpcode() == UO_Deref) 8737 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8738 // (assuming the deref expression is valid). 8739 return uOp->getSubExpr()->getType(); 8740 } 8741 // Technically, there should be a check for array subscript 8742 // expressions here, but the result of one is always an lvalue anyway. 8743 } 8744 ValueDecl *dcl = getPrimaryDecl(op); 8745 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8746 unsigned AddressOfError = AO_No_Error; 8747 8748 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8749 bool sfinae = (bool)isSFINAEContext(); 8750 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8751 : diag::ext_typecheck_addrof_temporary) 8752 << op->getType() << op->getSourceRange(); 8753 if (sfinae) 8754 return QualType(); 8755 // Materialize the temporary as an lvalue so that we can take its address. 8756 OrigOp = op = new (Context) 8757 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8758 } else if (isa<ObjCSelectorExpr>(op)) { 8759 return Context.getPointerType(op->getType()); 8760 } else if (lval == Expr::LV_MemberFunction) { 8761 // If it's an instance method, make a member pointer. 8762 // The expression must have exactly the form &A::foo. 8763 8764 // If the underlying expression isn't a decl ref, give up. 8765 if (!isa<DeclRefExpr>(op)) { 8766 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8767 << OrigOp.get()->getSourceRange(); 8768 return QualType(); 8769 } 8770 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8771 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8772 8773 // The id-expression was parenthesized. 8774 if (OrigOp.get() != DRE) { 8775 Diag(OpLoc, diag::err_parens_pointer_member_function) 8776 << OrigOp.get()->getSourceRange(); 8777 8778 // The method was named without a qualifier. 8779 } else if (!DRE->getQualifier()) { 8780 if (MD->getParent()->getName().empty()) 8781 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8782 << op->getSourceRange(); 8783 else { 8784 SmallString<32> Str; 8785 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8786 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8787 << op->getSourceRange() 8788 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8789 } 8790 } 8791 8792 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8793 if (isa<CXXDestructorDecl>(MD)) 8794 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8795 8796 return Context.getMemberPointerType(op->getType(), 8797 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8798 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8799 // C99 6.5.3.2p1 8800 // The operand must be either an l-value or a function designator 8801 if (!op->getType()->isFunctionType()) { 8802 // Use a special diagnostic for loads from property references. 8803 if (isa<PseudoObjectExpr>(op)) { 8804 AddressOfError = AO_Property_Expansion; 8805 } else { 8806 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8807 << op->getType() << op->getSourceRange(); 8808 return QualType(); 8809 } 8810 } 8811 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8812 // The operand cannot be a bit-field 8813 AddressOfError = AO_Bit_Field; 8814 } else if (op->getObjectKind() == OK_VectorComponent) { 8815 // The operand cannot be an element of a vector 8816 AddressOfError = AO_Vector_Element; 8817 } else if (dcl) { // C99 6.5.3.2p1 8818 // We have an lvalue with a decl. Make sure the decl is not declared 8819 // with the register storage-class specifier. 8820 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8821 // in C++ it is not error to take address of a register 8822 // variable (c++03 7.1.1P3) 8823 if (vd->getStorageClass() == SC_Register && 8824 !getLangOpts().CPlusPlus) { 8825 AddressOfError = AO_Register_Variable; 8826 } 8827 } else if (isa<FunctionTemplateDecl>(dcl)) { 8828 return Context.OverloadTy; 8829 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8830 // Okay: we can take the address of a field. 8831 // Could be a pointer to member, though, if there is an explicit 8832 // scope qualifier for the class. 8833 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8834 DeclContext *Ctx = dcl->getDeclContext(); 8835 if (Ctx && Ctx->isRecord()) { 8836 if (dcl->getType()->isReferenceType()) { 8837 Diag(OpLoc, 8838 diag::err_cannot_form_pointer_to_member_of_reference_type) 8839 << dcl->getDeclName() << dcl->getType(); 8840 return QualType(); 8841 } 8842 8843 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8844 Ctx = Ctx->getParent(); 8845 return Context.getMemberPointerType(op->getType(), 8846 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8847 } 8848 } 8849 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8850 llvm_unreachable("Unknown/unexpected decl type"); 8851 } 8852 8853 if (AddressOfError != AO_No_Error) { 8854 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8855 return QualType(); 8856 } 8857 8858 if (lval == Expr::LV_IncompleteVoidType) { 8859 // Taking the address of a void variable is technically illegal, but we 8860 // allow it in cases which are otherwise valid. 8861 // Example: "extern void x; void* y = &x;". 8862 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8863 } 8864 8865 // If the operand has type "type", the result has type "pointer to type". 8866 if (op->getType()->isObjCObjectType()) 8867 return Context.getObjCObjectPointerType(op->getType()); 8868 return Context.getPointerType(op->getType()); 8869} 8870 8871/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8872static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8873 SourceLocation OpLoc) { 8874 if (Op->isTypeDependent()) 8875 return S.Context.DependentTy; 8876 8877 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8878 if (ConvResult.isInvalid()) 8879 return QualType(); 8880 Op = ConvResult.take(); 8881 QualType OpTy = Op->getType(); 8882 QualType Result; 8883 8884 if (isa<CXXReinterpretCastExpr>(Op)) { 8885 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8886 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8887 Op->getSourceRange()); 8888 } 8889 8890 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8891 // is an incomplete type or void. It would be possible to warn about 8892 // dereferencing a void pointer, but it's completely well-defined, and such a 8893 // warning is unlikely to catch any mistakes. 8894 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8895 Result = PT->getPointeeType(); 8896 else if (const ObjCObjectPointerType *OPT = 8897 OpTy->getAs<ObjCObjectPointerType>()) 8898 Result = OPT->getPointeeType(); 8899 else { 8900 ExprResult PR = S.CheckPlaceholderExpr(Op); 8901 if (PR.isInvalid()) return QualType(); 8902 if (PR.take() != Op) 8903 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8904 } 8905 8906 if (Result.isNull()) { 8907 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8908 << OpTy << Op->getSourceRange(); 8909 return QualType(); 8910 } 8911 8912 // Dereferences are usually l-values... 8913 VK = VK_LValue; 8914 8915 // ...except that certain expressions are never l-values in C. 8916 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8917 VK = VK_RValue; 8918 8919 return Result; 8920} 8921 8922static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8923 tok::TokenKind Kind) { 8924 BinaryOperatorKind Opc; 8925 switch (Kind) { 8926 default: llvm_unreachable("Unknown binop!"); 8927 case tok::periodstar: Opc = BO_PtrMemD; break; 8928 case tok::arrowstar: Opc = BO_PtrMemI; break; 8929 case tok::star: Opc = BO_Mul; break; 8930 case tok::slash: Opc = BO_Div; break; 8931 case tok::percent: Opc = BO_Rem; break; 8932 case tok::plus: Opc = BO_Add; break; 8933 case tok::minus: Opc = BO_Sub; break; 8934 case tok::lessless: Opc = BO_Shl; break; 8935 case tok::greatergreater: Opc = BO_Shr; break; 8936 case tok::lessequal: Opc = BO_LE; break; 8937 case tok::less: Opc = BO_LT; break; 8938 case tok::greaterequal: Opc = BO_GE; break; 8939 case tok::greater: Opc = BO_GT; break; 8940 case tok::exclaimequal: Opc = BO_NE; break; 8941 case tok::equalequal: Opc = BO_EQ; break; 8942 case tok::amp: Opc = BO_And; break; 8943 case tok::caret: Opc = BO_Xor; break; 8944 case tok::pipe: Opc = BO_Or; break; 8945 case tok::ampamp: Opc = BO_LAnd; break; 8946 case tok::pipepipe: Opc = BO_LOr; break; 8947 case tok::equal: Opc = BO_Assign; break; 8948 case tok::starequal: Opc = BO_MulAssign; break; 8949 case tok::slashequal: Opc = BO_DivAssign; break; 8950 case tok::percentequal: Opc = BO_RemAssign; break; 8951 case tok::plusequal: Opc = BO_AddAssign; break; 8952 case tok::minusequal: Opc = BO_SubAssign; break; 8953 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8954 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8955 case tok::ampequal: Opc = BO_AndAssign; break; 8956 case tok::caretequal: Opc = BO_XorAssign; break; 8957 case tok::pipeequal: Opc = BO_OrAssign; break; 8958 case tok::comma: Opc = BO_Comma; break; 8959 } 8960 return Opc; 8961} 8962 8963static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8964 tok::TokenKind Kind) { 8965 UnaryOperatorKind Opc; 8966 switch (Kind) { 8967 default: llvm_unreachable("Unknown unary op!"); 8968 case tok::plusplus: Opc = UO_PreInc; break; 8969 case tok::minusminus: Opc = UO_PreDec; break; 8970 case tok::amp: Opc = UO_AddrOf; break; 8971 case tok::star: Opc = UO_Deref; break; 8972 case tok::plus: Opc = UO_Plus; break; 8973 case tok::minus: Opc = UO_Minus; break; 8974 case tok::tilde: Opc = UO_Not; break; 8975 case tok::exclaim: Opc = UO_LNot; break; 8976 case tok::kw___real: Opc = UO_Real; break; 8977 case tok::kw___imag: Opc = UO_Imag; break; 8978 case tok::kw___extension__: Opc = UO_Extension; break; 8979 } 8980 return Opc; 8981} 8982 8983/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8984/// This warning is only emitted for builtin assignment operations. It is also 8985/// suppressed in the event of macro expansions. 8986static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8987 SourceLocation OpLoc) { 8988 if (!S.ActiveTemplateInstantiations.empty()) 8989 return; 8990 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8991 return; 8992 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8993 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8994 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8995 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8996 if (!LHSDeclRef || !RHSDeclRef || 8997 LHSDeclRef->getLocation().isMacroID() || 8998 RHSDeclRef->getLocation().isMacroID()) 8999 return; 9000 const ValueDecl *LHSDecl = 9001 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9002 const ValueDecl *RHSDecl = 9003 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9004 if (LHSDecl != RHSDecl) 9005 return; 9006 if (LHSDecl->getType().isVolatileQualified()) 9007 return; 9008 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9009 if (RefTy->getPointeeType().isVolatileQualified()) 9010 return; 9011 9012 S.Diag(OpLoc, diag::warn_self_assignment) 9013 << LHSDeclRef->getType() 9014 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9015} 9016 9017/// Check if a bitwise-& is performed on an Objective-C pointer. This 9018/// is usually indicative of introspection within the Objective-C pointer. 9019static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9020 SourceLocation OpLoc) { 9021 if (!S.getLangOpts().ObjC1) 9022 return; 9023 9024 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9025 const Expr *LHS = L.get(); 9026 const Expr *RHS = R.get(); 9027 9028 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9029 ObjCPointerExpr = LHS; 9030 OtherExpr = RHS; 9031 } 9032 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9033 ObjCPointerExpr = RHS; 9034 OtherExpr = LHS; 9035 } 9036 9037 // This warning is deliberately made very specific to reduce false 9038 // positives with logic that uses '&' for hashing. This logic mainly 9039 // looks for code trying to introspect into tagged pointers, which 9040 // code should generally never do. 9041 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9042 unsigned Diag = diag::warn_objc_pointer_masking; 9043 // Determine if we are introspecting the result of performSelectorXXX. 9044 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9045 // Special case messages to -performSelector and friends, which 9046 // can return non-pointer values boxed in a pointer value. 9047 // Some clients may wish to silence warnings in this subcase. 9048 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9049 Selector S = ME->getSelector(); 9050 StringRef SelArg0 = S.getNameForSlot(0); 9051 if (SelArg0.startswith("performSelector")) 9052 Diag = diag::warn_objc_pointer_masking_performSelector; 9053 } 9054 9055 S.Diag(OpLoc, Diag) 9056 << ObjCPointerExpr->getSourceRange(); 9057 } 9058} 9059 9060/// CreateBuiltinBinOp - Creates a new built-in binary operation with 9061/// operator @p Opc at location @c TokLoc. This routine only supports 9062/// built-in operations; ActOnBinOp handles overloaded operators. 9063ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9064 BinaryOperatorKind Opc, 9065 Expr *LHSExpr, Expr *RHSExpr) { 9066 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9067 // The syntax only allows initializer lists on the RHS of assignment, 9068 // so we don't need to worry about accepting invalid code for 9069 // non-assignment operators. 9070 // C++11 5.17p9: 9071 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9072 // of x = {} is x = T(). 9073 InitializationKind Kind = 9074 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9075 InitializedEntity Entity = 9076 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9077 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9078 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9079 if (Init.isInvalid()) 9080 return Init; 9081 RHSExpr = Init.take(); 9082 } 9083 9084 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9085 QualType ResultTy; // Result type of the binary operator. 9086 // The following two variables are used for compound assignment operators 9087 QualType CompLHSTy; // Type of LHS after promotions for computation 9088 QualType CompResultTy; // Type of computation result 9089 ExprValueKind VK = VK_RValue; 9090 ExprObjectKind OK = OK_Ordinary; 9091 9092 switch (Opc) { 9093 case BO_Assign: 9094 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9095 if (getLangOpts().CPlusPlus && 9096 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9097 VK = LHS.get()->getValueKind(); 9098 OK = LHS.get()->getObjectKind(); 9099 } 9100 if (!ResultTy.isNull()) 9101 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9102 break; 9103 case BO_PtrMemD: 9104 case BO_PtrMemI: 9105 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9106 Opc == BO_PtrMemI); 9107 break; 9108 case BO_Mul: 9109 case BO_Div: 9110 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9111 Opc == BO_Div); 9112 break; 9113 case BO_Rem: 9114 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9115 break; 9116 case BO_Add: 9117 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9118 break; 9119 case BO_Sub: 9120 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9121 break; 9122 case BO_Shl: 9123 case BO_Shr: 9124 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9125 break; 9126 case BO_LE: 9127 case BO_LT: 9128 case BO_GE: 9129 case BO_GT: 9130 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9131 break; 9132 case BO_EQ: 9133 case BO_NE: 9134 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9135 break; 9136 case BO_And: 9137 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9138 case BO_Xor: 9139 case BO_Or: 9140 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9141 break; 9142 case BO_LAnd: 9143 case BO_LOr: 9144 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9145 break; 9146 case BO_MulAssign: 9147 case BO_DivAssign: 9148 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9149 Opc == BO_DivAssign); 9150 CompLHSTy = CompResultTy; 9151 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9152 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9153 break; 9154 case BO_RemAssign: 9155 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9156 CompLHSTy = CompResultTy; 9157 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9158 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9159 break; 9160 case BO_AddAssign: 9161 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9162 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9163 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9164 break; 9165 case BO_SubAssign: 9166 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9167 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9168 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9169 break; 9170 case BO_ShlAssign: 9171 case BO_ShrAssign: 9172 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9173 CompLHSTy = CompResultTy; 9174 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9175 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9176 break; 9177 case BO_AndAssign: 9178 case BO_XorAssign: 9179 case BO_OrAssign: 9180 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9181 CompLHSTy = CompResultTy; 9182 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9183 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9184 break; 9185 case BO_Comma: 9186 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9187 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9188 VK = RHS.get()->getValueKind(); 9189 OK = RHS.get()->getObjectKind(); 9190 } 9191 break; 9192 } 9193 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9194 return ExprError(); 9195 9196 // Check for array bounds violations for both sides of the BinaryOperator 9197 CheckArrayAccess(LHS.get()); 9198 CheckArrayAccess(RHS.get()); 9199 9200 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9201 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9202 &Context.Idents.get("object_setClass"), 9203 SourceLocation(), LookupOrdinaryName); 9204 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9205 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9206 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9207 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9208 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9209 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9210 } 9211 else 9212 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9213 } 9214 else if (const ObjCIvarRefExpr *OIRE = 9215 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9216 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9217 9218 if (CompResultTy.isNull()) 9219 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9220 ResultTy, VK, OK, OpLoc, 9221 FPFeatures.fp_contract)); 9222 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9223 OK_ObjCProperty) { 9224 VK = VK_LValue; 9225 OK = LHS.get()->getObjectKind(); 9226 } 9227 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9228 ResultTy, VK, OK, CompLHSTy, 9229 CompResultTy, OpLoc, 9230 FPFeatures.fp_contract)); 9231} 9232 9233/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9234/// operators are mixed in a way that suggests that the programmer forgot that 9235/// comparison operators have higher precedence. The most typical example of 9236/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9237static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9238 SourceLocation OpLoc, Expr *LHSExpr, 9239 Expr *RHSExpr) { 9240 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9241 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9242 9243 // Check that one of the sides is a comparison operator. 9244 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9245 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9246 if (!isLeftComp && !isRightComp) 9247 return; 9248 9249 // Bitwise operations are sometimes used as eager logical ops. 9250 // Don't diagnose this. 9251 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9252 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9253 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9254 return; 9255 9256 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9257 OpLoc) 9258 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9259 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9260 SourceRange ParensRange = isLeftComp ? 9261 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9262 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9263 9264 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9265 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9266 SuggestParentheses(Self, OpLoc, 9267 Self.PDiag(diag::note_precedence_silence) << OpStr, 9268 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9269 SuggestParentheses(Self, OpLoc, 9270 Self.PDiag(diag::note_precedence_bitwise_first) 9271 << BinaryOperator::getOpcodeStr(Opc), 9272 ParensRange); 9273} 9274 9275/// \brief It accepts a '&' expr that is inside a '|' one. 9276/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9277/// in parentheses. 9278static void 9279EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9280 BinaryOperator *Bop) { 9281 assert(Bop->getOpcode() == BO_And); 9282 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9283 << Bop->getSourceRange() << OpLoc; 9284 SuggestParentheses(Self, Bop->getOperatorLoc(), 9285 Self.PDiag(diag::note_precedence_silence) 9286 << Bop->getOpcodeStr(), 9287 Bop->getSourceRange()); 9288} 9289 9290/// \brief It accepts a '&&' expr that is inside a '||' one. 9291/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9292/// in parentheses. 9293static void 9294EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9295 BinaryOperator *Bop) { 9296 assert(Bop->getOpcode() == BO_LAnd); 9297 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9298 << Bop->getSourceRange() << OpLoc; 9299 SuggestParentheses(Self, Bop->getOperatorLoc(), 9300 Self.PDiag(diag::note_precedence_silence) 9301 << Bop->getOpcodeStr(), 9302 Bop->getSourceRange()); 9303} 9304 9305/// \brief Returns true if the given expression can be evaluated as a constant 9306/// 'true'. 9307static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9308 bool Res; 9309 return !E->isValueDependent() && 9310 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9311} 9312 9313/// \brief Returns true if the given expression can be evaluated as a constant 9314/// 'false'. 9315static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9316 bool Res; 9317 return !E->isValueDependent() && 9318 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9319} 9320 9321/// \brief Look for '&&' in the left hand of a '||' expr. 9322static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9323 Expr *LHSExpr, Expr *RHSExpr) { 9324 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9325 if (Bop->getOpcode() == BO_LAnd) { 9326 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9327 if (EvaluatesAsFalse(S, RHSExpr)) 9328 return; 9329 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9330 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9331 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9332 } else if (Bop->getOpcode() == BO_LOr) { 9333 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9334 // If it's "a || b && 1 || c" we didn't warn earlier for 9335 // "a || b && 1", but warn now. 9336 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9337 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9338 } 9339 } 9340 } 9341} 9342 9343/// \brief Look for '&&' in the right hand of a '||' expr. 9344static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9345 Expr *LHSExpr, Expr *RHSExpr) { 9346 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9347 if (Bop->getOpcode() == BO_LAnd) { 9348 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9349 if (EvaluatesAsFalse(S, LHSExpr)) 9350 return; 9351 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9352 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9353 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9354 } 9355 } 9356} 9357 9358/// \brief Look for '&' in the left or right hand of a '|' expr. 9359static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9360 Expr *OrArg) { 9361 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9362 if (Bop->getOpcode() == BO_And) 9363 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9364 } 9365} 9366 9367static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9368 Expr *SubExpr, StringRef Shift) { 9369 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9370 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9371 StringRef Op = Bop->getOpcodeStr(); 9372 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9373 << Bop->getSourceRange() << OpLoc << Shift << Op; 9374 SuggestParentheses(S, Bop->getOperatorLoc(), 9375 S.PDiag(diag::note_precedence_silence) << Op, 9376 Bop->getSourceRange()); 9377 } 9378 } 9379} 9380 9381static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9382 Expr *LHSExpr, Expr *RHSExpr) { 9383 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9384 if (!OCE) 9385 return; 9386 9387 FunctionDecl *FD = OCE->getDirectCallee(); 9388 if (!FD || !FD->isOverloadedOperator()) 9389 return; 9390 9391 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9392 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9393 return; 9394 9395 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9396 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9397 << (Kind == OO_LessLess); 9398 SuggestParentheses(S, OCE->getOperatorLoc(), 9399 S.PDiag(diag::note_precedence_silence) 9400 << (Kind == OO_LessLess ? "<<" : ">>"), 9401 OCE->getSourceRange()); 9402 SuggestParentheses(S, OpLoc, 9403 S.PDiag(diag::note_evaluate_comparison_first), 9404 SourceRange(OCE->getArg(1)->getLocStart(), 9405 RHSExpr->getLocEnd())); 9406} 9407 9408/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9409/// precedence. 9410static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9411 SourceLocation OpLoc, Expr *LHSExpr, 9412 Expr *RHSExpr){ 9413 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9414 if (BinaryOperator::isBitwiseOp(Opc)) 9415 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9416 9417 // Diagnose "arg1 & arg2 | arg3" 9418 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9419 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9420 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9421 } 9422 9423 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9424 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9425 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9426 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9427 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9428 } 9429 9430 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9431 || Opc == BO_Shr) { 9432 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9433 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9434 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9435 } 9436 9437 // Warn on overloaded shift operators and comparisons, such as: 9438 // cout << 5 == 4; 9439 if (BinaryOperator::isComparisonOp(Opc)) 9440 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9441} 9442 9443// Binary Operators. 'Tok' is the token for the operator. 9444ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9445 tok::TokenKind Kind, 9446 Expr *LHSExpr, Expr *RHSExpr) { 9447 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9448 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9449 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9450 9451 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9452 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9453 9454 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9455} 9456 9457/// Build an overloaded binary operator expression in the given scope. 9458static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9459 BinaryOperatorKind Opc, 9460 Expr *LHS, Expr *RHS) { 9461 // Find all of the overloaded operators visible from this 9462 // point. We perform both an operator-name lookup from the local 9463 // scope and an argument-dependent lookup based on the types of 9464 // the arguments. 9465 UnresolvedSet<16> Functions; 9466 OverloadedOperatorKind OverOp 9467 = BinaryOperator::getOverloadedOperator(Opc); 9468 if (Sc && OverOp != OO_None) 9469 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9470 RHS->getType(), Functions); 9471 9472 // Build the (potentially-overloaded, potentially-dependent) 9473 // binary operation. 9474 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9475} 9476 9477ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9478 BinaryOperatorKind Opc, 9479 Expr *LHSExpr, Expr *RHSExpr) { 9480 // We want to end up calling one of checkPseudoObjectAssignment 9481 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9482 // both expressions are overloadable or either is type-dependent), 9483 // or CreateBuiltinBinOp (in any other case). We also want to get 9484 // any placeholder types out of the way. 9485 9486 // Handle pseudo-objects in the LHS. 9487 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9488 // Assignments with a pseudo-object l-value need special analysis. 9489 if (pty->getKind() == BuiltinType::PseudoObject && 9490 BinaryOperator::isAssignmentOp(Opc)) 9491 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9492 9493 // Don't resolve overloads if the other type is overloadable. 9494 if (pty->getKind() == BuiltinType::Overload) { 9495 // We can't actually test that if we still have a placeholder, 9496 // though. Fortunately, none of the exceptions we see in that 9497 // code below are valid when the LHS is an overload set. Note 9498 // that an overload set can be dependently-typed, but it never 9499 // instantiates to having an overloadable type. 9500 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9501 if (resolvedRHS.isInvalid()) return ExprError(); 9502 RHSExpr = resolvedRHS.take(); 9503 9504 if (RHSExpr->isTypeDependent() || 9505 RHSExpr->getType()->isOverloadableType()) 9506 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9507 } 9508 9509 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9510 if (LHS.isInvalid()) return ExprError(); 9511 LHSExpr = LHS.take(); 9512 } 9513 9514 // Handle pseudo-objects in the RHS. 9515 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9516 // An overload in the RHS can potentially be resolved by the type 9517 // being assigned to. 9518 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9519 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9520 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9521 9522 if (LHSExpr->getType()->isOverloadableType()) 9523 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9524 9525 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9526 } 9527 9528 // Don't resolve overloads if the other type is overloadable. 9529 if (pty->getKind() == BuiltinType::Overload && 9530 LHSExpr->getType()->isOverloadableType()) 9531 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9532 9533 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9534 if (!resolvedRHS.isUsable()) return ExprError(); 9535 RHSExpr = resolvedRHS.take(); 9536 } 9537 9538 if (getLangOpts().CPlusPlus) { 9539 // If either expression is type-dependent, always build an 9540 // overloaded op. 9541 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9542 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9543 9544 // Otherwise, build an overloaded op if either expression has an 9545 // overloadable type. 9546 if (LHSExpr->getType()->isOverloadableType() || 9547 RHSExpr->getType()->isOverloadableType()) 9548 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9549 } 9550 9551 // Build a built-in binary operation. 9552 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9553} 9554 9555ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9556 UnaryOperatorKind Opc, 9557 Expr *InputExpr) { 9558 ExprResult Input = Owned(InputExpr); 9559 ExprValueKind VK = VK_RValue; 9560 ExprObjectKind OK = OK_Ordinary; 9561 QualType resultType; 9562 switch (Opc) { 9563 case UO_PreInc: 9564 case UO_PreDec: 9565 case UO_PostInc: 9566 case UO_PostDec: 9567 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9568 Opc == UO_PreInc || 9569 Opc == UO_PostInc, 9570 Opc == UO_PreInc || 9571 Opc == UO_PreDec); 9572 break; 9573 case UO_AddrOf: 9574 resultType = CheckAddressOfOperand(Input, OpLoc); 9575 break; 9576 case UO_Deref: { 9577 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9578 if (Input.isInvalid()) return ExprError(); 9579 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9580 break; 9581 } 9582 case UO_Plus: 9583 case UO_Minus: 9584 Input = UsualUnaryConversions(Input.take()); 9585 if (Input.isInvalid()) return ExprError(); 9586 resultType = Input.get()->getType(); 9587 if (resultType->isDependentType()) 9588 break; 9589 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9590 resultType->isVectorType()) 9591 break; 9592 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9593 Opc == UO_Plus && 9594 resultType->isPointerType()) 9595 break; 9596 9597 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9598 << resultType << Input.get()->getSourceRange()); 9599 9600 case UO_Not: // bitwise complement 9601 Input = UsualUnaryConversions(Input.take()); 9602 if (Input.isInvalid()) 9603 return ExprError(); 9604 resultType = Input.get()->getType(); 9605 if (resultType->isDependentType()) 9606 break; 9607 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9608 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9609 // C99 does not support '~' for complex conjugation. 9610 Diag(OpLoc, diag::ext_integer_complement_complex) 9611 << resultType << Input.get()->getSourceRange(); 9612 else if (resultType->hasIntegerRepresentation()) 9613 break; 9614 else if (resultType->isExtVectorType()) { 9615 if (Context.getLangOpts().OpenCL) { 9616 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9617 // on vector float types. 9618 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9619 if (!T->isIntegerType()) 9620 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9621 << resultType << Input.get()->getSourceRange()); 9622 } 9623 break; 9624 } else { 9625 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9626 << resultType << Input.get()->getSourceRange()); 9627 } 9628 break; 9629 9630 case UO_LNot: // logical negation 9631 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9632 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9633 if (Input.isInvalid()) return ExprError(); 9634 resultType = Input.get()->getType(); 9635 9636 // Though we still have to promote half FP to float... 9637 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9638 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9639 resultType = Context.FloatTy; 9640 } 9641 9642 if (resultType->isDependentType()) 9643 break; 9644 if (resultType->isScalarType()) { 9645 // C99 6.5.3.3p1: ok, fallthrough; 9646 if (Context.getLangOpts().CPlusPlus) { 9647 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9648 // operand contextually converted to bool. 9649 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9650 ScalarTypeToBooleanCastKind(resultType)); 9651 } else if (Context.getLangOpts().OpenCL && 9652 Context.getLangOpts().OpenCLVersion < 120) { 9653 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9654 // operate on scalar float types. 9655 if (!resultType->isIntegerType()) 9656 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9657 << resultType << Input.get()->getSourceRange()); 9658 } 9659 } else if (resultType->isExtVectorType()) { 9660 if (Context.getLangOpts().OpenCL && 9661 Context.getLangOpts().OpenCLVersion < 120) { 9662 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9663 // operate on vector float types. 9664 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9665 if (!T->isIntegerType()) 9666 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9667 << resultType << Input.get()->getSourceRange()); 9668 } 9669 // Vector logical not returns the signed variant of the operand type. 9670 resultType = GetSignedVectorType(resultType); 9671 break; 9672 } else { 9673 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9674 << resultType << Input.get()->getSourceRange()); 9675 } 9676 9677 // LNot always has type int. C99 6.5.3.3p5. 9678 // In C++, it's bool. C++ 5.3.1p8 9679 resultType = Context.getLogicalOperationType(); 9680 break; 9681 case UO_Real: 9682 case UO_Imag: 9683 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9684 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9685 // complex l-values to ordinary l-values and all other values to r-values. 9686 if (Input.isInvalid()) return ExprError(); 9687 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9688 if (Input.get()->getValueKind() != VK_RValue && 9689 Input.get()->getObjectKind() == OK_Ordinary) 9690 VK = Input.get()->getValueKind(); 9691 } else if (!getLangOpts().CPlusPlus) { 9692 // In C, a volatile scalar is read by __imag. In C++, it is not. 9693 Input = DefaultLvalueConversion(Input.take()); 9694 } 9695 break; 9696 case UO_Extension: 9697 resultType = Input.get()->getType(); 9698 VK = Input.get()->getValueKind(); 9699 OK = Input.get()->getObjectKind(); 9700 break; 9701 } 9702 if (resultType.isNull() || Input.isInvalid()) 9703 return ExprError(); 9704 9705 // Check for array bounds violations in the operand of the UnaryOperator, 9706 // except for the '*' and '&' operators that have to be handled specially 9707 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9708 // that are explicitly defined as valid by the standard). 9709 if (Opc != UO_AddrOf && Opc != UO_Deref) 9710 CheckArrayAccess(Input.get()); 9711 9712 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9713 VK, OK, OpLoc)); 9714} 9715 9716/// \brief Determine whether the given expression is a qualified member 9717/// access expression, of a form that could be turned into a pointer to member 9718/// with the address-of operator. 9719static bool isQualifiedMemberAccess(Expr *E) { 9720 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9721 if (!DRE->getQualifier()) 9722 return false; 9723 9724 ValueDecl *VD = DRE->getDecl(); 9725 if (!VD->isCXXClassMember()) 9726 return false; 9727 9728 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9729 return true; 9730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9731 return Method->isInstance(); 9732 9733 return false; 9734 } 9735 9736 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9737 if (!ULE->getQualifier()) 9738 return false; 9739 9740 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9741 DEnd = ULE->decls_end(); 9742 D != DEnd; ++D) { 9743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9744 if (Method->isInstance()) 9745 return true; 9746 } else { 9747 // Overload set does not contain methods. 9748 break; 9749 } 9750 } 9751 9752 return false; 9753 } 9754 9755 return false; 9756} 9757 9758ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9759 UnaryOperatorKind Opc, Expr *Input) { 9760 // First things first: handle placeholders so that the 9761 // overloaded-operator check considers the right type. 9762 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9763 // Increment and decrement of pseudo-object references. 9764 if (pty->getKind() == BuiltinType::PseudoObject && 9765 UnaryOperator::isIncrementDecrementOp(Opc)) 9766 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9767 9768 // extension is always a builtin operator. 9769 if (Opc == UO_Extension) 9770 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9771 9772 // & gets special logic for several kinds of placeholder. 9773 // The builtin code knows what to do. 9774 if (Opc == UO_AddrOf && 9775 (pty->getKind() == BuiltinType::Overload || 9776 pty->getKind() == BuiltinType::UnknownAny || 9777 pty->getKind() == BuiltinType::BoundMember)) 9778 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9779 9780 // Anything else needs to be handled now. 9781 ExprResult Result = CheckPlaceholderExpr(Input); 9782 if (Result.isInvalid()) return ExprError(); 9783 Input = Result.take(); 9784 } 9785 9786 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9787 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9788 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9789 // Find all of the overloaded operators visible from this 9790 // point. We perform both an operator-name lookup from the local 9791 // scope and an argument-dependent lookup based on the types of 9792 // the arguments. 9793 UnresolvedSet<16> Functions; 9794 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9795 if (S && OverOp != OO_None) 9796 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9797 Functions); 9798 9799 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9800 } 9801 9802 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9803} 9804 9805// Unary Operators. 'Tok' is the token for the operator. 9806ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9807 tok::TokenKind Op, Expr *Input) { 9808 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9809} 9810 9811/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9812ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9813 LabelDecl *TheDecl) { 9814 TheDecl->markUsed(Context); 9815 // Create the AST node. The address of a label always has type 'void*'. 9816 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9817 Context.getPointerType(Context.VoidTy))); 9818} 9819 9820/// Given the last statement in a statement-expression, check whether 9821/// the result is a producing expression (like a call to an 9822/// ns_returns_retained function) and, if so, rebuild it to hoist the 9823/// release out of the full-expression. Otherwise, return null. 9824/// Cannot fail. 9825static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9826 // Should always be wrapped with one of these. 9827 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9828 if (!cleanups) return 0; 9829 9830 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9831 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9832 return 0; 9833 9834 // Splice out the cast. This shouldn't modify any interesting 9835 // features of the statement. 9836 Expr *producer = cast->getSubExpr(); 9837 assert(producer->getType() == cast->getType()); 9838 assert(producer->getValueKind() == cast->getValueKind()); 9839 cleanups->setSubExpr(producer); 9840 return cleanups; 9841} 9842 9843void Sema::ActOnStartStmtExpr() { 9844 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9845} 9846 9847void Sema::ActOnStmtExprError() { 9848 // Note that function is also called by TreeTransform when leaving a 9849 // StmtExpr scope without rebuilding anything. 9850 9851 DiscardCleanupsInEvaluationContext(); 9852 PopExpressionEvaluationContext(); 9853} 9854 9855ExprResult 9856Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9857 SourceLocation RPLoc) { // "({..})" 9858 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9859 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9860 9861 if (hasAnyUnrecoverableErrorsInThisFunction()) 9862 DiscardCleanupsInEvaluationContext(); 9863 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9864 PopExpressionEvaluationContext(); 9865 9866 bool isFileScope 9867 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9868 if (isFileScope) 9869 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9870 9871 // FIXME: there are a variety of strange constraints to enforce here, for 9872 // example, it is not possible to goto into a stmt expression apparently. 9873 // More semantic analysis is needed. 9874 9875 // If there are sub stmts in the compound stmt, take the type of the last one 9876 // as the type of the stmtexpr. 9877 QualType Ty = Context.VoidTy; 9878 bool StmtExprMayBindToTemp = false; 9879 if (!Compound->body_empty()) { 9880 Stmt *LastStmt = Compound->body_back(); 9881 LabelStmt *LastLabelStmt = 0; 9882 // If LastStmt is a label, skip down through into the body. 9883 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9884 LastLabelStmt = Label; 9885 LastStmt = Label->getSubStmt(); 9886 } 9887 9888 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9889 // Do function/array conversion on the last expression, but not 9890 // lvalue-to-rvalue. However, initialize an unqualified type. 9891 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9892 if (LastExpr.isInvalid()) 9893 return ExprError(); 9894 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9895 9896 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9897 // In ARC, if the final expression ends in a consume, splice 9898 // the consume out and bind it later. In the alternate case 9899 // (when dealing with a retainable type), the result 9900 // initialization will create a produce. In both cases the 9901 // result will be +1, and we'll need to balance that out with 9902 // a bind. 9903 if (Expr *rebuiltLastStmt 9904 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9905 LastExpr = rebuiltLastStmt; 9906 } else { 9907 LastExpr = PerformCopyInitialization( 9908 InitializedEntity::InitializeResult(LPLoc, 9909 Ty, 9910 false), 9911 SourceLocation(), 9912 LastExpr); 9913 } 9914 9915 if (LastExpr.isInvalid()) 9916 return ExprError(); 9917 if (LastExpr.get() != 0) { 9918 if (!LastLabelStmt) 9919 Compound->setLastStmt(LastExpr.take()); 9920 else 9921 LastLabelStmt->setSubStmt(LastExpr.take()); 9922 StmtExprMayBindToTemp = true; 9923 } 9924 } 9925 } 9926 } 9927 9928 // FIXME: Check that expression type is complete/non-abstract; statement 9929 // expressions are not lvalues. 9930 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9931 if (StmtExprMayBindToTemp) 9932 return MaybeBindToTemporary(ResStmtExpr); 9933 return Owned(ResStmtExpr); 9934} 9935 9936ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9937 TypeSourceInfo *TInfo, 9938 OffsetOfComponent *CompPtr, 9939 unsigned NumComponents, 9940 SourceLocation RParenLoc) { 9941 QualType ArgTy = TInfo->getType(); 9942 bool Dependent = ArgTy->isDependentType(); 9943 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9944 9945 // We must have at least one component that refers to the type, and the first 9946 // one is known to be a field designator. Verify that the ArgTy represents 9947 // a struct/union/class. 9948 if (!Dependent && !ArgTy->isRecordType()) 9949 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9950 << ArgTy << TypeRange); 9951 9952 // Type must be complete per C99 7.17p3 because a declaring a variable 9953 // with an incomplete type would be ill-formed. 9954 if (!Dependent 9955 && RequireCompleteType(BuiltinLoc, ArgTy, 9956 diag::err_offsetof_incomplete_type, TypeRange)) 9957 return ExprError(); 9958 9959 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9960 // GCC extension, diagnose them. 9961 // FIXME: This diagnostic isn't actually visible because the location is in 9962 // a system header! 9963 if (NumComponents != 1) 9964 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9965 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9966 9967 bool DidWarnAboutNonPOD = false; 9968 QualType CurrentType = ArgTy; 9969 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9970 SmallVector<OffsetOfNode, 4> Comps; 9971 SmallVector<Expr*, 4> Exprs; 9972 for (unsigned i = 0; i != NumComponents; ++i) { 9973 const OffsetOfComponent &OC = CompPtr[i]; 9974 if (OC.isBrackets) { 9975 // Offset of an array sub-field. TODO: Should we allow vector elements? 9976 if (!CurrentType->isDependentType()) { 9977 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9978 if(!AT) 9979 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9980 << CurrentType); 9981 CurrentType = AT->getElementType(); 9982 } else 9983 CurrentType = Context.DependentTy; 9984 9985 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9986 if (IdxRval.isInvalid()) 9987 return ExprError(); 9988 Expr *Idx = IdxRval.take(); 9989 9990 // The expression must be an integral expression. 9991 // FIXME: An integral constant expression? 9992 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9993 !Idx->getType()->isIntegerType()) 9994 return ExprError(Diag(Idx->getLocStart(), 9995 diag::err_typecheck_subscript_not_integer) 9996 << Idx->getSourceRange()); 9997 9998 // Record this array index. 9999 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10000 Exprs.push_back(Idx); 10001 continue; 10002 } 10003 10004 // Offset of a field. 10005 if (CurrentType->isDependentType()) { 10006 // We have the offset of a field, but we can't look into the dependent 10007 // type. Just record the identifier of the field. 10008 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10009 CurrentType = Context.DependentTy; 10010 continue; 10011 } 10012 10013 // We need to have a complete type to look into. 10014 if (RequireCompleteType(OC.LocStart, CurrentType, 10015 diag::err_offsetof_incomplete_type)) 10016 return ExprError(); 10017 10018 // Look for the designated field. 10019 const RecordType *RC = CurrentType->getAs<RecordType>(); 10020 if (!RC) 10021 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10022 << CurrentType); 10023 RecordDecl *RD = RC->getDecl(); 10024 10025 // C++ [lib.support.types]p5: 10026 // The macro offsetof accepts a restricted set of type arguments in this 10027 // International Standard. type shall be a POD structure or a POD union 10028 // (clause 9). 10029 // C++11 [support.types]p4: 10030 // If type is not a standard-layout class (Clause 9), the results are 10031 // undefined. 10032 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10033 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10034 unsigned DiagID = 10035 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10036 : diag::warn_offsetof_non_pod_type; 10037 10038 if (!IsSafe && !DidWarnAboutNonPOD && 10039 DiagRuntimeBehavior(BuiltinLoc, 0, 10040 PDiag(DiagID) 10041 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10042 << CurrentType)) 10043 DidWarnAboutNonPOD = true; 10044 } 10045 10046 // Look for the field. 10047 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10048 LookupQualifiedName(R, RD); 10049 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10050 IndirectFieldDecl *IndirectMemberDecl = 0; 10051 if (!MemberDecl) { 10052 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10053 MemberDecl = IndirectMemberDecl->getAnonField(); 10054 } 10055 10056 if (!MemberDecl) 10057 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10058 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10059 OC.LocEnd)); 10060 10061 // C99 7.17p3: 10062 // (If the specified member is a bit-field, the behavior is undefined.) 10063 // 10064 // We diagnose this as an error. 10065 if (MemberDecl->isBitField()) { 10066 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10067 << MemberDecl->getDeclName() 10068 << SourceRange(BuiltinLoc, RParenLoc); 10069 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10070 return ExprError(); 10071 } 10072 10073 RecordDecl *Parent = MemberDecl->getParent(); 10074 if (IndirectMemberDecl) 10075 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10076 10077 // If the member was found in a base class, introduce OffsetOfNodes for 10078 // the base class indirections. 10079 CXXBasePaths Paths; 10080 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10081 if (Paths.getDetectedVirtual()) { 10082 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10083 << MemberDecl->getDeclName() 10084 << SourceRange(BuiltinLoc, RParenLoc); 10085 return ExprError(); 10086 } 10087 10088 CXXBasePath &Path = Paths.front(); 10089 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10090 B != BEnd; ++B) 10091 Comps.push_back(OffsetOfNode(B->Base)); 10092 } 10093 10094 if (IndirectMemberDecl) { 10095 for (IndirectFieldDecl::chain_iterator FI = 10096 IndirectMemberDecl->chain_begin(), 10097 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 10098 assert(isa<FieldDecl>(*FI)); 10099 Comps.push_back(OffsetOfNode(OC.LocStart, 10100 cast<FieldDecl>(*FI), OC.LocEnd)); 10101 } 10102 } else 10103 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10104 10105 CurrentType = MemberDecl->getType().getNonReferenceType(); 10106 } 10107 10108 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10109 TInfo, Comps, Exprs, RParenLoc)); 10110} 10111 10112ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10113 SourceLocation BuiltinLoc, 10114 SourceLocation TypeLoc, 10115 ParsedType ParsedArgTy, 10116 OffsetOfComponent *CompPtr, 10117 unsigned NumComponents, 10118 SourceLocation RParenLoc) { 10119 10120 TypeSourceInfo *ArgTInfo; 10121 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10122 if (ArgTy.isNull()) 10123 return ExprError(); 10124 10125 if (!ArgTInfo) 10126 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10127 10128 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10129 RParenLoc); 10130} 10131 10132 10133ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10134 Expr *CondExpr, 10135 Expr *LHSExpr, Expr *RHSExpr, 10136 SourceLocation RPLoc) { 10137 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10138 10139 ExprValueKind VK = VK_RValue; 10140 ExprObjectKind OK = OK_Ordinary; 10141 QualType resType; 10142 bool ValueDependent = false; 10143 bool CondIsTrue = false; 10144 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10145 resType = Context.DependentTy; 10146 ValueDependent = true; 10147 } else { 10148 // The conditional expression is required to be a constant expression. 10149 llvm::APSInt condEval(32); 10150 ExprResult CondICE 10151 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10152 diag::err_typecheck_choose_expr_requires_constant, false); 10153 if (CondICE.isInvalid()) 10154 return ExprError(); 10155 CondExpr = CondICE.take(); 10156 CondIsTrue = condEval.getZExtValue(); 10157 10158 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10159 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10160 10161 resType = ActiveExpr->getType(); 10162 ValueDependent = ActiveExpr->isValueDependent(); 10163 VK = ActiveExpr->getValueKind(); 10164 OK = ActiveExpr->getObjectKind(); 10165 } 10166 10167 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10168 resType, VK, OK, RPLoc, CondIsTrue, 10169 resType->isDependentType(), 10170 ValueDependent)); 10171} 10172 10173//===----------------------------------------------------------------------===// 10174// Clang Extensions. 10175//===----------------------------------------------------------------------===// 10176 10177/// ActOnBlockStart - This callback is invoked when a block literal is started. 10178void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10179 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10180 10181 if (LangOpts.CPlusPlus) { 10182 Decl *ManglingContextDecl; 10183 if (MangleNumberingContext *MCtx = 10184 getCurrentMangleNumberContext(Block->getDeclContext(), 10185 ManglingContextDecl)) { 10186 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10187 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10188 } 10189 } 10190 10191 PushBlockScope(CurScope, Block); 10192 CurContext->addDecl(Block); 10193 if (CurScope) 10194 PushDeclContext(CurScope, Block); 10195 else 10196 CurContext = Block; 10197 10198 getCurBlock()->HasImplicitReturnType = true; 10199 10200 // Enter a new evaluation context to insulate the block from any 10201 // cleanups from the enclosing full-expression. 10202 PushExpressionEvaluationContext(PotentiallyEvaluated); 10203} 10204 10205void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10206 Scope *CurScope) { 10207 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10208 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10209 BlockScopeInfo *CurBlock = getCurBlock(); 10210 10211 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10212 QualType T = Sig->getType(); 10213 10214 // FIXME: We should allow unexpanded parameter packs here, but that would, 10215 // in turn, make the block expression contain unexpanded parameter packs. 10216 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10217 // Drop the parameters. 10218 FunctionProtoType::ExtProtoInfo EPI; 10219 EPI.HasTrailingReturn = false; 10220 EPI.TypeQuals |= DeclSpec::TQ_const; 10221 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10222 Sig = Context.getTrivialTypeSourceInfo(T); 10223 } 10224 10225 // GetTypeForDeclarator always produces a function type for a block 10226 // literal signature. Furthermore, it is always a FunctionProtoType 10227 // unless the function was written with a typedef. 10228 assert(T->isFunctionType() && 10229 "GetTypeForDeclarator made a non-function block signature"); 10230 10231 // Look for an explicit signature in that function type. 10232 FunctionProtoTypeLoc ExplicitSignature; 10233 10234 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10235 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10236 10237 // Check whether that explicit signature was synthesized by 10238 // GetTypeForDeclarator. If so, don't save that as part of the 10239 // written signature. 10240 if (ExplicitSignature.getLocalRangeBegin() == 10241 ExplicitSignature.getLocalRangeEnd()) { 10242 // This would be much cheaper if we stored TypeLocs instead of 10243 // TypeSourceInfos. 10244 TypeLoc Result = ExplicitSignature.getResultLoc(); 10245 unsigned Size = Result.getFullDataSize(); 10246 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10247 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10248 10249 ExplicitSignature = FunctionProtoTypeLoc(); 10250 } 10251 } 10252 10253 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10254 CurBlock->FunctionType = T; 10255 10256 const FunctionType *Fn = T->getAs<FunctionType>(); 10257 QualType RetTy = Fn->getResultType(); 10258 bool isVariadic = 10259 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10260 10261 CurBlock->TheDecl->setIsVariadic(isVariadic); 10262 10263 // Context.DependentTy is used as a placeholder for a missing block 10264 // return type. TODO: what should we do with declarators like: 10265 // ^ * { ... } 10266 // If the answer is "apply template argument deduction".... 10267 if (RetTy != Context.DependentTy) { 10268 CurBlock->ReturnType = RetTy; 10269 CurBlock->TheDecl->setBlockMissingReturnType(false); 10270 CurBlock->HasImplicitReturnType = false; 10271 } 10272 10273 // Push block parameters from the declarator if we had them. 10274 SmallVector<ParmVarDecl*, 8> Params; 10275 if (ExplicitSignature) { 10276 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 10277 ParmVarDecl *Param = ExplicitSignature.getArg(I); 10278 if (Param->getIdentifier() == 0 && 10279 !Param->isImplicit() && 10280 !Param->isInvalidDecl() && 10281 !getLangOpts().CPlusPlus) 10282 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10283 Params.push_back(Param); 10284 } 10285 10286 // Fake up parameter variables if we have a typedef, like 10287 // ^ fntype { ... } 10288 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10289 for (FunctionProtoType::arg_type_iterator 10290 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 10291 ParmVarDecl *Param = 10292 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10293 ParamInfo.getLocStart(), 10294 *I); 10295 Params.push_back(Param); 10296 } 10297 } 10298 10299 // Set the parameters on the block decl. 10300 if (!Params.empty()) { 10301 CurBlock->TheDecl->setParams(Params); 10302 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10303 CurBlock->TheDecl->param_end(), 10304 /*CheckParameterNames=*/false); 10305 } 10306 10307 // Finally we can process decl attributes. 10308 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10309 10310 // Put the parameter variables in scope. 10311 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 10312 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 10313 (*AI)->setOwningFunction(CurBlock->TheDecl); 10314 10315 // If this has an identifier, add it to the scope stack. 10316 if ((*AI)->getIdentifier()) { 10317 CheckShadow(CurBlock->TheScope, *AI); 10318 10319 PushOnScopeChains(*AI, CurBlock->TheScope); 10320 } 10321 } 10322} 10323 10324/// ActOnBlockError - If there is an error parsing a block, this callback 10325/// is invoked to pop the information about the block from the action impl. 10326void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10327 // Leave the expression-evaluation context. 10328 DiscardCleanupsInEvaluationContext(); 10329 PopExpressionEvaluationContext(); 10330 10331 // Pop off CurBlock, handle nested blocks. 10332 PopDeclContext(); 10333 PopFunctionScopeInfo(); 10334} 10335 10336/// ActOnBlockStmtExpr - This is called when the body of a block statement 10337/// literal was successfully completed. ^(int x){...} 10338ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10339 Stmt *Body, Scope *CurScope) { 10340 // If blocks are disabled, emit an error. 10341 if (!LangOpts.Blocks) 10342 Diag(CaretLoc, diag::err_blocks_disable); 10343 10344 // Leave the expression-evaluation context. 10345 if (hasAnyUnrecoverableErrorsInThisFunction()) 10346 DiscardCleanupsInEvaluationContext(); 10347 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10348 PopExpressionEvaluationContext(); 10349 10350 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10351 10352 if (BSI->HasImplicitReturnType) 10353 deduceClosureReturnType(*BSI); 10354 10355 PopDeclContext(); 10356 10357 QualType RetTy = Context.VoidTy; 10358 if (!BSI->ReturnType.isNull()) 10359 RetTy = BSI->ReturnType; 10360 10361 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 10362 QualType BlockTy; 10363 10364 // Set the captured variables on the block. 10365 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10366 SmallVector<BlockDecl::Capture, 4> Captures; 10367 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10368 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10369 if (Cap.isThisCapture()) 10370 continue; 10371 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10372 Cap.isNested(), Cap.getInitExpr()); 10373 Captures.push_back(NewCap); 10374 } 10375 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10376 BSI->CXXThisCaptureIndex != 0); 10377 10378 // If the user wrote a function type in some form, try to use that. 10379 if (!BSI->FunctionType.isNull()) { 10380 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10381 10382 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10383 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10384 10385 // Turn protoless block types into nullary block types. 10386 if (isa<FunctionNoProtoType>(FTy)) { 10387 FunctionProtoType::ExtProtoInfo EPI; 10388 EPI.ExtInfo = Ext; 10389 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10390 10391 // Otherwise, if we don't need to change anything about the function type, 10392 // preserve its sugar structure. 10393 } else if (FTy->getResultType() == RetTy && 10394 (!NoReturn || FTy->getNoReturnAttr())) { 10395 BlockTy = BSI->FunctionType; 10396 10397 // Otherwise, make the minimal modifications to the function type. 10398 } else { 10399 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10400 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10401 EPI.TypeQuals = 0; // FIXME: silently? 10402 EPI.ExtInfo = Ext; 10403 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI); 10404 } 10405 10406 // If we don't have a function type, just build one from nothing. 10407 } else { 10408 FunctionProtoType::ExtProtoInfo EPI; 10409 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10410 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10411 } 10412 10413 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10414 BSI->TheDecl->param_end()); 10415 BlockTy = Context.getBlockPointerType(BlockTy); 10416 10417 // If needed, diagnose invalid gotos and switches in the block. 10418 if (getCurFunction()->NeedsScopeChecking() && 10419 !hasAnyUnrecoverableErrorsInThisFunction() && 10420 !PP.isCodeCompletionEnabled()) 10421 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10422 10423 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10424 10425 // Try to apply the named return value optimization. We have to check again 10426 // if we can do this, though, because blocks keep return statements around 10427 // to deduce an implicit return type. 10428 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10429 !BSI->TheDecl->isDependentContext()) 10430 computeNRVO(Body, getCurBlock()); 10431 10432 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10433 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10434 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10435 10436 // If the block isn't obviously global, i.e. it captures anything at 10437 // all, then we need to do a few things in the surrounding context: 10438 if (Result->getBlockDecl()->hasCaptures()) { 10439 // First, this expression has a new cleanup object. 10440 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10441 ExprNeedsCleanups = true; 10442 10443 // It also gets a branch-protected scope if any of the captured 10444 // variables needs destruction. 10445 for (BlockDecl::capture_const_iterator 10446 ci = Result->getBlockDecl()->capture_begin(), 10447 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10448 const VarDecl *var = ci->getVariable(); 10449 if (var->getType().isDestructedType() != QualType::DK_none) { 10450 getCurFunction()->setHasBranchProtectedScope(); 10451 break; 10452 } 10453 } 10454 } 10455 10456 return Owned(Result); 10457} 10458 10459ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10460 Expr *E, ParsedType Ty, 10461 SourceLocation RPLoc) { 10462 TypeSourceInfo *TInfo; 10463 GetTypeFromParser(Ty, &TInfo); 10464 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10465} 10466 10467ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10468 Expr *E, TypeSourceInfo *TInfo, 10469 SourceLocation RPLoc) { 10470 Expr *OrigExpr = E; 10471 10472 // Get the va_list type 10473 QualType VaListType = Context.getBuiltinVaListType(); 10474 if (VaListType->isArrayType()) { 10475 // Deal with implicit array decay; for example, on x86-64, 10476 // va_list is an array, but it's supposed to decay to 10477 // a pointer for va_arg. 10478 VaListType = Context.getArrayDecayedType(VaListType); 10479 // Make sure the input expression also decays appropriately. 10480 ExprResult Result = UsualUnaryConversions(E); 10481 if (Result.isInvalid()) 10482 return ExprError(); 10483 E = Result.take(); 10484 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10485 // If va_list is a record type and we are compiling in C++ mode, 10486 // check the argument using reference binding. 10487 InitializedEntity Entity 10488 = InitializedEntity::InitializeParameter(Context, 10489 Context.getLValueReferenceType(VaListType), false); 10490 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10491 if (Init.isInvalid()) 10492 return ExprError(); 10493 E = Init.takeAs<Expr>(); 10494 } else { 10495 // Otherwise, the va_list argument must be an l-value because 10496 // it is modified by va_arg. 10497 if (!E->isTypeDependent() && 10498 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10499 return ExprError(); 10500 } 10501 10502 if (!E->isTypeDependent() && 10503 !Context.hasSameType(VaListType, E->getType())) { 10504 return ExprError(Diag(E->getLocStart(), 10505 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10506 << OrigExpr->getType() << E->getSourceRange()); 10507 } 10508 10509 if (!TInfo->getType()->isDependentType()) { 10510 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10511 diag::err_second_parameter_to_va_arg_incomplete, 10512 TInfo->getTypeLoc())) 10513 return ExprError(); 10514 10515 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10516 TInfo->getType(), 10517 diag::err_second_parameter_to_va_arg_abstract, 10518 TInfo->getTypeLoc())) 10519 return ExprError(); 10520 10521 if (!TInfo->getType().isPODType(Context)) { 10522 Diag(TInfo->getTypeLoc().getBeginLoc(), 10523 TInfo->getType()->isObjCLifetimeType() 10524 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10525 : diag::warn_second_parameter_to_va_arg_not_pod) 10526 << TInfo->getType() 10527 << TInfo->getTypeLoc().getSourceRange(); 10528 } 10529 10530 // Check for va_arg where arguments of the given type will be promoted 10531 // (i.e. this va_arg is guaranteed to have undefined behavior). 10532 QualType PromoteType; 10533 if (TInfo->getType()->isPromotableIntegerType()) { 10534 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10535 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10536 PromoteType = QualType(); 10537 } 10538 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10539 PromoteType = Context.DoubleTy; 10540 if (!PromoteType.isNull()) 10541 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10542 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10543 << TInfo->getType() 10544 << PromoteType 10545 << TInfo->getTypeLoc().getSourceRange()); 10546 } 10547 10548 QualType T = TInfo->getType().getNonLValueExprType(Context); 10549 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10550} 10551 10552ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10553 // The type of __null will be int or long, depending on the size of 10554 // pointers on the target. 10555 QualType Ty; 10556 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10557 if (pw == Context.getTargetInfo().getIntWidth()) 10558 Ty = Context.IntTy; 10559 else if (pw == Context.getTargetInfo().getLongWidth()) 10560 Ty = Context.LongTy; 10561 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10562 Ty = Context.LongLongTy; 10563 else { 10564 llvm_unreachable("I don't know size of pointer!"); 10565 } 10566 10567 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10568} 10569 10570static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10571 Expr *SrcExpr, FixItHint &Hint, 10572 bool &IsNSString) { 10573 if (!SemaRef.getLangOpts().ObjC1) 10574 return; 10575 10576 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10577 if (!PT) 10578 return; 10579 10580 // Check if the destination is of type 'id'. 10581 if (!PT->isObjCIdType()) { 10582 // Check if the destination is the 'NSString' interface. 10583 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10584 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10585 return; 10586 IsNSString = true; 10587 } 10588 10589 // Ignore any parens, implicit casts (should only be 10590 // array-to-pointer decays), and not-so-opaque values. The last is 10591 // important for making this trigger for property assignments. 10592 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10593 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10594 if (OV->getSourceExpr()) 10595 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10596 10597 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10598 if (!SL || !SL->isAscii()) 10599 return; 10600 10601 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10602} 10603 10604bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10605 SourceLocation Loc, 10606 QualType DstType, QualType SrcType, 10607 Expr *SrcExpr, AssignmentAction Action, 10608 bool *Complained) { 10609 if (Complained) 10610 *Complained = false; 10611 10612 // Decode the result (notice that AST's are still created for extensions). 10613 bool CheckInferredResultType = false; 10614 bool isInvalid = false; 10615 unsigned DiagKind = 0; 10616 FixItHint Hint; 10617 ConversionFixItGenerator ConvHints; 10618 bool MayHaveConvFixit = false; 10619 bool MayHaveFunctionDiff = false; 10620 bool IsNSString = false; 10621 10622 switch (ConvTy) { 10623 case Compatible: 10624 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10625 return false; 10626 10627 case PointerToInt: 10628 DiagKind = diag::ext_typecheck_convert_pointer_int; 10629 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10630 MayHaveConvFixit = true; 10631 break; 10632 case IntToPointer: 10633 DiagKind = diag::ext_typecheck_convert_int_pointer; 10634 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10635 MayHaveConvFixit = true; 10636 break; 10637 case IncompatiblePointer: 10638 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString); 10639 DiagKind = 10640 (Action == AA_Passing_CFAudited ? 10641 diag::err_arc_typecheck_convert_incompatible_pointer : 10642 diag::ext_typecheck_convert_incompatible_pointer); 10643 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10644 SrcType->isObjCObjectPointerType(); 10645 if (Hint.isNull() && !CheckInferredResultType) { 10646 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10647 } 10648 else if (CheckInferredResultType) { 10649 SrcType = SrcType.getUnqualifiedType(); 10650 DstType = DstType.getUnqualifiedType(); 10651 } 10652 else if (IsNSString && !Hint.isNull()) 10653 DiagKind = diag::warn_missing_atsign_prefix; 10654 MayHaveConvFixit = true; 10655 break; 10656 case IncompatiblePointerSign: 10657 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10658 break; 10659 case FunctionVoidPointer: 10660 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10661 break; 10662 case IncompatiblePointerDiscardsQualifiers: { 10663 // Perform array-to-pointer decay if necessary. 10664 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10665 10666 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10667 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10668 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10669 DiagKind = diag::err_typecheck_incompatible_address_space; 10670 break; 10671 10672 10673 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10674 DiagKind = diag::err_typecheck_incompatible_ownership; 10675 break; 10676 } 10677 10678 llvm_unreachable("unknown error case for discarding qualifiers!"); 10679 // fallthrough 10680 } 10681 case CompatiblePointerDiscardsQualifiers: 10682 // If the qualifiers lost were because we were applying the 10683 // (deprecated) C++ conversion from a string literal to a char* 10684 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10685 // Ideally, this check would be performed in 10686 // checkPointerTypesForAssignment. However, that would require a 10687 // bit of refactoring (so that the second argument is an 10688 // expression, rather than a type), which should be done as part 10689 // of a larger effort to fix checkPointerTypesForAssignment for 10690 // C++ semantics. 10691 if (getLangOpts().CPlusPlus && 10692 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10693 return false; 10694 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10695 break; 10696 case IncompatibleNestedPointerQualifiers: 10697 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10698 break; 10699 case IntToBlockPointer: 10700 DiagKind = diag::err_int_to_block_pointer; 10701 break; 10702 case IncompatibleBlockPointer: 10703 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10704 break; 10705 case IncompatibleObjCQualifiedId: 10706 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10707 // it can give a more specific diagnostic. 10708 DiagKind = diag::warn_incompatible_qualified_id; 10709 break; 10710 case IncompatibleVectors: 10711 DiagKind = diag::warn_incompatible_vectors; 10712 break; 10713 case IncompatibleObjCWeakRef: 10714 DiagKind = diag::err_arc_weak_unavailable_assign; 10715 break; 10716 case Incompatible: 10717 DiagKind = diag::err_typecheck_convert_incompatible; 10718 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10719 MayHaveConvFixit = true; 10720 isInvalid = true; 10721 MayHaveFunctionDiff = true; 10722 break; 10723 } 10724 10725 QualType FirstType, SecondType; 10726 switch (Action) { 10727 case AA_Assigning: 10728 case AA_Initializing: 10729 // The destination type comes first. 10730 FirstType = DstType; 10731 SecondType = SrcType; 10732 break; 10733 10734 case AA_Returning: 10735 case AA_Passing: 10736 case AA_Passing_CFAudited: 10737 case AA_Converting: 10738 case AA_Sending: 10739 case AA_Casting: 10740 // The source type comes first. 10741 FirstType = SrcType; 10742 SecondType = DstType; 10743 break; 10744 } 10745 10746 PartialDiagnostic FDiag = PDiag(DiagKind); 10747 if (Action == AA_Passing_CFAudited) 10748 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10749 else 10750 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10751 10752 // If we can fix the conversion, suggest the FixIts. 10753 assert(ConvHints.isNull() || Hint.isNull()); 10754 if (!ConvHints.isNull()) { 10755 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10756 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10757 FDiag << *HI; 10758 } else { 10759 FDiag << Hint; 10760 } 10761 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10762 10763 if (MayHaveFunctionDiff) 10764 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10765 10766 Diag(Loc, FDiag); 10767 10768 if (SecondType == Context.OverloadTy) 10769 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10770 FirstType); 10771 10772 if (CheckInferredResultType) 10773 EmitRelatedResultTypeNote(SrcExpr); 10774 10775 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10776 EmitRelatedResultTypeNoteForReturn(DstType); 10777 10778 if (Complained) 10779 *Complained = true; 10780 return isInvalid; 10781} 10782 10783ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10784 llvm::APSInt *Result) { 10785 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10786 public: 10787 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10788 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10789 } 10790 } Diagnoser; 10791 10792 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10793} 10794 10795ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10796 llvm::APSInt *Result, 10797 unsigned DiagID, 10798 bool AllowFold) { 10799 class IDDiagnoser : public VerifyICEDiagnoser { 10800 unsigned DiagID; 10801 10802 public: 10803 IDDiagnoser(unsigned DiagID) 10804 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10805 10806 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10807 S.Diag(Loc, DiagID) << SR; 10808 } 10809 } Diagnoser(DiagID); 10810 10811 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10812} 10813 10814void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10815 SourceRange SR) { 10816 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10817} 10818 10819ExprResult 10820Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10821 VerifyICEDiagnoser &Diagnoser, 10822 bool AllowFold) { 10823 SourceLocation DiagLoc = E->getLocStart(); 10824 10825 if (getLangOpts().CPlusPlus11) { 10826 // C++11 [expr.const]p5: 10827 // If an expression of literal class type is used in a context where an 10828 // integral constant expression is required, then that class type shall 10829 // have a single non-explicit conversion function to an integral or 10830 // unscoped enumeration type 10831 ExprResult Converted; 10832 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10833 public: 10834 CXX11ConvertDiagnoser(bool Silent) 10835 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10836 Silent, true) {} 10837 10838 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10839 QualType T) { 10840 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10841 } 10842 10843 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10844 Sema &S, SourceLocation Loc, QualType T) { 10845 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10846 } 10847 10848 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10849 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10850 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10851 } 10852 10853 virtual SemaDiagnosticBuilder noteExplicitConv( 10854 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10855 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10856 << ConvTy->isEnumeralType() << ConvTy; 10857 } 10858 10859 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10860 Sema &S, SourceLocation Loc, QualType T) { 10861 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10862 } 10863 10864 virtual SemaDiagnosticBuilder noteAmbiguous( 10865 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10866 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10867 << ConvTy->isEnumeralType() << ConvTy; 10868 } 10869 10870 virtual SemaDiagnosticBuilder diagnoseConversion( 10871 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10872 llvm_unreachable("conversion functions are permitted"); 10873 } 10874 } ConvertDiagnoser(Diagnoser.Suppress); 10875 10876 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10877 ConvertDiagnoser); 10878 if (Converted.isInvalid()) 10879 return Converted; 10880 E = Converted.take(); 10881 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10882 return ExprError(); 10883 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10884 // An ICE must be of integral or unscoped enumeration type. 10885 if (!Diagnoser.Suppress) 10886 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10887 return ExprError(); 10888 } 10889 10890 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10891 // in the non-ICE case. 10892 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10893 if (Result) 10894 *Result = E->EvaluateKnownConstInt(Context); 10895 return Owned(E); 10896 } 10897 10898 Expr::EvalResult EvalResult; 10899 SmallVector<PartialDiagnosticAt, 8> Notes; 10900 EvalResult.Diag = &Notes; 10901 10902 // Try to evaluate the expression, and produce diagnostics explaining why it's 10903 // not a constant expression as a side-effect. 10904 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10905 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10906 10907 // In C++11, we can rely on diagnostics being produced for any expression 10908 // which is not a constant expression. If no diagnostics were produced, then 10909 // this is a constant expression. 10910 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10911 if (Result) 10912 *Result = EvalResult.Val.getInt(); 10913 return Owned(E); 10914 } 10915 10916 // If our only note is the usual "invalid subexpression" note, just point 10917 // the caret at its location rather than producing an essentially 10918 // redundant note. 10919 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10920 diag::note_invalid_subexpr_in_const_expr) { 10921 DiagLoc = Notes[0].first; 10922 Notes.clear(); 10923 } 10924 10925 if (!Folded || !AllowFold) { 10926 if (!Diagnoser.Suppress) { 10927 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10928 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10929 Diag(Notes[I].first, Notes[I].second); 10930 } 10931 10932 return ExprError(); 10933 } 10934 10935 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10936 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10937 Diag(Notes[I].first, Notes[I].second); 10938 10939 if (Result) 10940 *Result = EvalResult.Val.getInt(); 10941 return Owned(E); 10942} 10943 10944namespace { 10945 // Handle the case where we conclude a expression which we speculatively 10946 // considered to be unevaluated is actually evaluated. 10947 class TransformToPE : public TreeTransform<TransformToPE> { 10948 typedef TreeTransform<TransformToPE> BaseTransform; 10949 10950 public: 10951 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10952 10953 // Make sure we redo semantic analysis 10954 bool AlwaysRebuild() { return true; } 10955 10956 // Make sure we handle LabelStmts correctly. 10957 // FIXME: This does the right thing, but maybe we need a more general 10958 // fix to TreeTransform? 10959 StmtResult TransformLabelStmt(LabelStmt *S) { 10960 S->getDecl()->setStmt(0); 10961 return BaseTransform::TransformLabelStmt(S); 10962 } 10963 10964 // We need to special-case DeclRefExprs referring to FieldDecls which 10965 // are not part of a member pointer formation; normal TreeTransforming 10966 // doesn't catch this case because of the way we represent them in the AST. 10967 // FIXME: This is a bit ugly; is it really the best way to handle this 10968 // case? 10969 // 10970 // Error on DeclRefExprs referring to FieldDecls. 10971 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10972 if (isa<FieldDecl>(E->getDecl()) && 10973 !SemaRef.isUnevaluatedContext()) 10974 return SemaRef.Diag(E->getLocation(), 10975 diag::err_invalid_non_static_member_use) 10976 << E->getDecl() << E->getSourceRange(); 10977 10978 return BaseTransform::TransformDeclRefExpr(E); 10979 } 10980 10981 // Exception: filter out member pointer formation 10982 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10983 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10984 return E; 10985 10986 return BaseTransform::TransformUnaryOperator(E); 10987 } 10988 10989 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10990 // Lambdas never need to be transformed. 10991 return E; 10992 } 10993 }; 10994} 10995 10996ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10997 assert(isUnevaluatedContext() && 10998 "Should only transform unevaluated expressions"); 10999 ExprEvalContexts.back().Context = 11000 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11001 if (isUnevaluatedContext()) 11002 return E; 11003 return TransformToPE(*this).TransformExpr(E); 11004} 11005 11006void 11007Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11008 Decl *LambdaContextDecl, 11009 bool IsDecltype) { 11010 ExprEvalContexts.push_back( 11011 ExpressionEvaluationContextRecord(NewContext, 11012 ExprCleanupObjects.size(), 11013 ExprNeedsCleanups, 11014 LambdaContextDecl, 11015 IsDecltype)); 11016 ExprNeedsCleanups = false; 11017 if (!MaybeODRUseExprs.empty()) 11018 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11019} 11020 11021void 11022Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11023 ReuseLambdaContextDecl_t, 11024 bool IsDecltype) { 11025 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11026 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11027} 11028 11029void Sema::PopExpressionEvaluationContext() { 11030 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11031 11032 if (!Rec.Lambdas.empty()) { 11033 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11034 unsigned D; 11035 if (Rec.isUnevaluated()) { 11036 // C++11 [expr.prim.lambda]p2: 11037 // A lambda-expression shall not appear in an unevaluated operand 11038 // (Clause 5). 11039 D = diag::err_lambda_unevaluated_operand; 11040 } else { 11041 // C++1y [expr.const]p2: 11042 // A conditional-expression e is a core constant expression unless the 11043 // evaluation of e, following the rules of the abstract machine, would 11044 // evaluate [...] a lambda-expression. 11045 D = diag::err_lambda_in_constant_expression; 11046 } 11047 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11048 Diag(Rec.Lambdas[I]->getLocStart(), D); 11049 } else { 11050 // Mark the capture expressions odr-used. This was deferred 11051 // during lambda expression creation. 11052 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11053 LambdaExpr *Lambda = Rec.Lambdas[I]; 11054 for (LambdaExpr::capture_init_iterator 11055 C = Lambda->capture_init_begin(), 11056 CEnd = Lambda->capture_init_end(); 11057 C != CEnd; ++C) { 11058 MarkDeclarationsReferencedInExpr(*C); 11059 } 11060 } 11061 } 11062 } 11063 11064 // When are coming out of an unevaluated context, clear out any 11065 // temporaries that we may have created as part of the evaluation of 11066 // the expression in that context: they aren't relevant because they 11067 // will never be constructed. 11068 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11069 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11070 ExprCleanupObjects.end()); 11071 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11072 CleanupVarDeclMarking(); 11073 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11074 // Otherwise, merge the contexts together. 11075 } else { 11076 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11077 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11078 Rec.SavedMaybeODRUseExprs.end()); 11079 } 11080 11081 // Pop the current expression evaluation context off the stack. 11082 ExprEvalContexts.pop_back(); 11083} 11084 11085void Sema::DiscardCleanupsInEvaluationContext() { 11086 ExprCleanupObjects.erase( 11087 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11088 ExprCleanupObjects.end()); 11089 ExprNeedsCleanups = false; 11090 MaybeODRUseExprs.clear(); 11091} 11092 11093ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11094 if (!E->getType()->isVariablyModifiedType()) 11095 return E; 11096 return TransformToPotentiallyEvaluated(E); 11097} 11098 11099static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11100 // Do not mark anything as "used" within a dependent context; wait for 11101 // an instantiation. 11102 if (SemaRef.CurContext->isDependentContext()) 11103 return false; 11104 11105 switch (SemaRef.ExprEvalContexts.back().Context) { 11106 case Sema::Unevaluated: 11107 case Sema::UnevaluatedAbstract: 11108 // We are in an expression that is not potentially evaluated; do nothing. 11109 // (Depending on how you read the standard, we actually do need to do 11110 // something here for null pointer constants, but the standard's 11111 // definition of a null pointer constant is completely crazy.) 11112 return false; 11113 11114 case Sema::ConstantEvaluated: 11115 case Sema::PotentiallyEvaluated: 11116 // We are in a potentially evaluated expression (or a constant-expression 11117 // in C++03); we need to do implicit template instantiation, implicitly 11118 // define class members, and mark most declarations as used. 11119 return true; 11120 11121 case Sema::PotentiallyEvaluatedIfUsed: 11122 // Referenced declarations will only be used if the construct in the 11123 // containing expression is used. 11124 return false; 11125 } 11126 llvm_unreachable("Invalid context"); 11127} 11128 11129/// \brief Mark a function referenced, and check whether it is odr-used 11130/// (C++ [basic.def.odr]p2, C99 6.9p3) 11131void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11132 assert(Func && "No function?"); 11133 11134 Func->setReferenced(); 11135 11136 // C++11 [basic.def.odr]p3: 11137 // A function whose name appears as a potentially-evaluated expression is 11138 // odr-used if it is the unique lookup result or the selected member of a 11139 // set of overloaded functions [...]. 11140 // 11141 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11142 // can just check that here. Skip the rest of this function if we've already 11143 // marked the function as used. 11144 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11145 // C++11 [temp.inst]p3: 11146 // Unless a function template specialization has been explicitly 11147 // instantiated or explicitly specialized, the function template 11148 // specialization is implicitly instantiated when the specialization is 11149 // referenced in a context that requires a function definition to exist. 11150 // 11151 // We consider constexpr function templates to be referenced in a context 11152 // that requires a definition to exist whenever they are referenced. 11153 // 11154 // FIXME: This instantiates constexpr functions too frequently. If this is 11155 // really an unevaluated context (and we're not just in the definition of a 11156 // function template or overload resolution or other cases which we 11157 // incorrectly consider to be unevaluated contexts), and we're not in a 11158 // subexpression which we actually need to evaluate (for instance, a 11159 // template argument, array bound or an expression in a braced-init-list), 11160 // we are not permitted to instantiate this constexpr function definition. 11161 // 11162 // FIXME: This also implicitly defines special members too frequently. They 11163 // are only supposed to be implicitly defined if they are odr-used, but they 11164 // are not odr-used from constant expressions in unevaluated contexts. 11165 // However, they cannot be referenced if they are deleted, and they are 11166 // deleted whenever the implicit definition of the special member would 11167 // fail. 11168 if (!Func->isConstexpr() || Func->getBody()) 11169 return; 11170 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11171 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11172 return; 11173 } 11174 11175 // Note that this declaration has been used. 11176 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11177 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11178 if (Constructor->isDefaultConstructor()) { 11179 if (Constructor->isTrivial()) 11180 return; 11181 if (!Constructor->isUsed(false)) 11182 DefineImplicitDefaultConstructor(Loc, Constructor); 11183 } else if (Constructor->isCopyConstructor()) { 11184 if (!Constructor->isUsed(false)) 11185 DefineImplicitCopyConstructor(Loc, Constructor); 11186 } else if (Constructor->isMoveConstructor()) { 11187 if (!Constructor->isUsed(false)) 11188 DefineImplicitMoveConstructor(Loc, Constructor); 11189 } 11190 } else if (Constructor->getInheritedConstructor()) { 11191 if (!Constructor->isUsed(false)) 11192 DefineInheritingConstructor(Loc, Constructor); 11193 } 11194 11195 MarkVTableUsed(Loc, Constructor->getParent()); 11196 } else if (CXXDestructorDecl *Destructor = 11197 dyn_cast<CXXDestructorDecl>(Func)) { 11198 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 11199 !Destructor->isUsed(false)) 11200 DefineImplicitDestructor(Loc, Destructor); 11201 if (Destructor->isVirtual()) 11202 MarkVTableUsed(Loc, Destructor->getParent()); 11203 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11204 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 11205 MethodDecl->isOverloadedOperator() && 11206 MethodDecl->getOverloadedOperator() == OO_Equal) { 11207 if (!MethodDecl->isUsed(false)) { 11208 if (MethodDecl->isCopyAssignmentOperator()) 11209 DefineImplicitCopyAssignment(Loc, MethodDecl); 11210 else 11211 DefineImplicitMoveAssignment(Loc, MethodDecl); 11212 } 11213 } else if (isa<CXXConversionDecl>(MethodDecl) && 11214 MethodDecl->getParent()->isLambda()) { 11215 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 11216 if (Conversion->isLambdaToBlockPointerConversion()) 11217 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11218 else 11219 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11220 } else if (MethodDecl->isVirtual()) 11221 MarkVTableUsed(Loc, MethodDecl->getParent()); 11222 } 11223 11224 // Recursive functions should be marked when used from another function. 11225 // FIXME: Is this really right? 11226 if (CurContext == Func) return; 11227 11228 // Resolve the exception specification for any function which is 11229 // used: CodeGen will need it. 11230 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11231 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11232 ResolveExceptionSpec(Loc, FPT); 11233 11234 // Implicit instantiation of function templates and member functions of 11235 // class templates. 11236 if (Func->isImplicitlyInstantiable()) { 11237 bool AlreadyInstantiated = false; 11238 SourceLocation PointOfInstantiation = Loc; 11239 if (FunctionTemplateSpecializationInfo *SpecInfo 11240 = Func->getTemplateSpecializationInfo()) { 11241 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11242 SpecInfo->setPointOfInstantiation(Loc); 11243 else if (SpecInfo->getTemplateSpecializationKind() 11244 == TSK_ImplicitInstantiation) { 11245 AlreadyInstantiated = true; 11246 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11247 } 11248 } else if (MemberSpecializationInfo *MSInfo 11249 = Func->getMemberSpecializationInfo()) { 11250 if (MSInfo->getPointOfInstantiation().isInvalid()) 11251 MSInfo->setPointOfInstantiation(Loc); 11252 else if (MSInfo->getTemplateSpecializationKind() 11253 == TSK_ImplicitInstantiation) { 11254 AlreadyInstantiated = true; 11255 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11256 } 11257 } 11258 11259 if (!AlreadyInstantiated || Func->isConstexpr()) { 11260 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11261 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11262 ActiveTemplateInstantiations.size()) 11263 PendingLocalImplicitInstantiations.push_back( 11264 std::make_pair(Func, PointOfInstantiation)); 11265 else if (Func->isConstexpr()) 11266 // Do not defer instantiations of constexpr functions, to avoid the 11267 // expression evaluator needing to call back into Sema if it sees a 11268 // call to such a function. 11269 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11270 else { 11271 PendingInstantiations.push_back(std::make_pair(Func, 11272 PointOfInstantiation)); 11273 // Notify the consumer that a function was implicitly instantiated. 11274 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11275 } 11276 } 11277 } else { 11278 // Walk redefinitions, as some of them may be instantiable. 11279 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 11280 e(Func->redecls_end()); i != e; ++i) { 11281 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11282 MarkFunctionReferenced(Loc, *i); 11283 } 11284 } 11285 11286 // Keep track of used but undefined functions. 11287 if (!Func->isDefined()) { 11288 if (mightHaveNonExternalLinkage(Func)) 11289 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11290 else if (Func->getMostRecentDecl()->isInlined() && 11291 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11292 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11293 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11294 } 11295 11296 // Normally the most current decl is marked used while processing the use and 11297 // any subsequent decls are marked used by decl merging. This fails with 11298 // template instantiation since marking can happen at the end of the file 11299 // and, because of the two phase lookup, this function is called with at 11300 // decl in the middle of a decl chain. We loop to maintain the invariant 11301 // that once a decl is used, all decls after it are also used. 11302 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11303 F->markUsed(Context); 11304 if (F == Func) 11305 break; 11306 } 11307} 11308 11309static void 11310diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11311 VarDecl *var, DeclContext *DC) { 11312 DeclContext *VarDC = var->getDeclContext(); 11313 11314 // If the parameter still belongs to the translation unit, then 11315 // we're actually just using one parameter in the declaration of 11316 // the next. 11317 if (isa<ParmVarDecl>(var) && 11318 isa<TranslationUnitDecl>(VarDC)) 11319 return; 11320 11321 // For C code, don't diagnose about capture if we're not actually in code 11322 // right now; it's impossible to write a non-constant expression outside of 11323 // function context, so we'll get other (more useful) diagnostics later. 11324 // 11325 // For C++, things get a bit more nasty... it would be nice to suppress this 11326 // diagnostic for certain cases like using a local variable in an array bound 11327 // for a member of a local class, but the correct predicate is not obvious. 11328 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11329 return; 11330 11331 if (isa<CXXMethodDecl>(VarDC) && 11332 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11333 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11334 << var->getIdentifier(); 11335 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11336 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11337 << var->getIdentifier() << fn->getDeclName(); 11338 } else if (isa<BlockDecl>(VarDC)) { 11339 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11340 << var->getIdentifier(); 11341 } else { 11342 // FIXME: Is there any other context where a local variable can be 11343 // declared? 11344 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11345 << var->getIdentifier(); 11346 } 11347 11348 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11349 << var->getIdentifier(); 11350 11351 // FIXME: Add additional diagnostic info about class etc. which prevents 11352 // capture. 11353} 11354 11355 11356static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11357 bool &SubCapturesAreNested, 11358 QualType &CaptureType, 11359 QualType &DeclRefType) { 11360 // Check whether we've already captured it. 11361 if (CSI->CaptureMap.count(Var)) { 11362 // If we found a capture, any subcaptures are nested. 11363 SubCapturesAreNested = true; 11364 11365 // Retrieve the capture type for this variable. 11366 CaptureType = CSI->getCapture(Var).getCaptureType(); 11367 11368 // Compute the type of an expression that refers to this variable. 11369 DeclRefType = CaptureType.getNonReferenceType(); 11370 11371 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11372 if (Cap.isCopyCapture() && 11373 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11374 DeclRefType.addConst(); 11375 return true; 11376 } 11377 return false; 11378} 11379 11380// Only block literals, captured statements, and lambda expressions can 11381// capture; other scopes don't work. 11382static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11383 SourceLocation Loc, 11384 const bool Diagnose, Sema &S) { 11385 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11386 return getLambdaAwareParentOfDeclContext(DC); 11387 else { 11388 if (Diagnose) 11389 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11390 } 11391 return 0; 11392} 11393 11394// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11395// certain types of variables (unnamed, variably modified types etc.) 11396// so check for eligibility. 11397static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11398 SourceLocation Loc, 11399 const bool Diagnose, Sema &S) { 11400 11401 bool IsBlock = isa<BlockScopeInfo>(CSI); 11402 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11403 11404 // Lambdas are not allowed to capture unnamed variables 11405 // (e.g. anonymous unions). 11406 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11407 // assuming that's the intent. 11408 if (IsLambda && !Var->getDeclName()) { 11409 if (Diagnose) { 11410 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11411 S.Diag(Var->getLocation(), diag::note_declared_at); 11412 } 11413 return false; 11414 } 11415 11416 // Prohibit variably-modified types; they're difficult to deal with. 11417 if (Var->getType()->isVariablyModifiedType()) { 11418 if (Diagnose) { 11419 if (IsBlock) 11420 S.Diag(Loc, diag::err_ref_vm_type); 11421 else 11422 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11423 S.Diag(Var->getLocation(), diag::note_previous_decl) 11424 << Var->getDeclName(); 11425 } 11426 return false; 11427 } 11428 // Prohibit structs with flexible array members too. 11429 // We cannot capture what is in the tail end of the struct. 11430 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11431 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11432 if (Diagnose) { 11433 if (IsBlock) 11434 S.Diag(Loc, diag::err_ref_flexarray_type); 11435 else 11436 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11437 << Var->getDeclName(); 11438 S.Diag(Var->getLocation(), diag::note_previous_decl) 11439 << Var->getDeclName(); 11440 } 11441 return false; 11442 } 11443 } 11444 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11445 // Lambdas and captured statements are not allowed to capture __block 11446 // variables; they don't support the expected semantics. 11447 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11448 if (Diagnose) { 11449 S.Diag(Loc, diag::err_capture_block_variable) 11450 << Var->getDeclName() << !IsLambda; 11451 S.Diag(Var->getLocation(), diag::note_previous_decl) 11452 << Var->getDeclName(); 11453 } 11454 return false; 11455 } 11456 11457 return true; 11458} 11459 11460// Returns true if the capture by block was successful. 11461static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11462 SourceLocation Loc, 11463 const bool BuildAndDiagnose, 11464 QualType &CaptureType, 11465 QualType &DeclRefType, 11466 const bool Nested, 11467 Sema &S) { 11468 Expr *CopyExpr = 0; 11469 bool ByRef = false; 11470 11471 // Blocks are not allowed to capture arrays. 11472 if (CaptureType->isArrayType()) { 11473 if (BuildAndDiagnose) { 11474 S.Diag(Loc, diag::err_ref_array_type); 11475 S.Diag(Var->getLocation(), diag::note_previous_decl) 11476 << Var->getDeclName(); 11477 } 11478 return false; 11479 } 11480 11481 // Forbid the block-capture of autoreleasing variables. 11482 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11483 if (BuildAndDiagnose) { 11484 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11485 << /*block*/ 0; 11486 S.Diag(Var->getLocation(), diag::note_previous_decl) 11487 << Var->getDeclName(); 11488 } 11489 return false; 11490 } 11491 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11492 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11493 // Block capture by reference does not change the capture or 11494 // declaration reference types. 11495 ByRef = true; 11496 } else { 11497 // Block capture by copy introduces 'const'. 11498 CaptureType = CaptureType.getNonReferenceType().withConst(); 11499 DeclRefType = CaptureType; 11500 11501 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11502 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11503 // The capture logic needs the destructor, so make sure we mark it. 11504 // Usually this is unnecessary because most local variables have 11505 // their destructors marked at declaration time, but parameters are 11506 // an exception because it's technically only the call site that 11507 // actually requires the destructor. 11508 if (isa<ParmVarDecl>(Var)) 11509 S.FinalizeVarWithDestructor(Var, Record); 11510 11511 // Enter a new evaluation context to insulate the copy 11512 // full-expression. 11513 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11514 11515 // According to the blocks spec, the capture of a variable from 11516 // the stack requires a const copy constructor. This is not true 11517 // of the copy/move done to move a __block variable to the heap. 11518 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11519 DeclRefType.withConst(), 11520 VK_LValue, Loc); 11521 11522 ExprResult Result 11523 = S.PerformCopyInitialization( 11524 InitializedEntity::InitializeBlock(Var->getLocation(), 11525 CaptureType, false), 11526 Loc, S.Owned(DeclRef)); 11527 11528 // Build a full-expression copy expression if initialization 11529 // succeeded and used a non-trivial constructor. Recover from 11530 // errors by pretending that the copy isn't necessary. 11531 if (!Result.isInvalid() && 11532 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11533 ->isTrivial()) { 11534 Result = S.MaybeCreateExprWithCleanups(Result); 11535 CopyExpr = Result.take(); 11536 } 11537 } 11538 } 11539 } 11540 11541 // Actually capture the variable. 11542 if (BuildAndDiagnose) 11543 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11544 SourceLocation(), CaptureType, CopyExpr); 11545 11546 return true; 11547 11548} 11549 11550 11551/// \brief Capture the given variable in the captured region. 11552static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11553 VarDecl *Var, 11554 SourceLocation Loc, 11555 const bool BuildAndDiagnose, 11556 QualType &CaptureType, 11557 QualType &DeclRefType, 11558 const bool RefersToEnclosingLocal, 11559 Sema &S) { 11560 11561 // By default, capture variables by reference. 11562 bool ByRef = true; 11563 // Using an LValue reference type is consistent with Lambdas (see below). 11564 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11565 Expr *CopyExpr = 0; 11566 if (BuildAndDiagnose) { 11567 // The current implementation assumes that all variables are captured 11568 // by references. Since there is no capture by copy, no expression evaluation 11569 // will be needed. 11570 // 11571 RecordDecl *RD = RSI->TheRecordDecl; 11572 11573 FieldDecl *Field 11574 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11575 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11576 0, false, ICIS_NoInit); 11577 Field->setImplicit(true); 11578 Field->setAccess(AS_private); 11579 RD->addDecl(Field); 11580 11581 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11582 DeclRefType, VK_LValue, Loc); 11583 Var->setReferenced(true); 11584 Var->markUsed(S.Context); 11585 } 11586 11587 // Actually capture the variable. 11588 if (BuildAndDiagnose) 11589 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11590 SourceLocation(), CaptureType, CopyExpr); 11591 11592 11593 return true; 11594} 11595 11596/// \brief Create a field within the lambda class for the variable 11597/// being captured. Handle Array captures. 11598static ExprResult addAsFieldToClosureType(Sema &S, 11599 LambdaScopeInfo *LSI, 11600 VarDecl *Var, QualType FieldType, 11601 QualType DeclRefType, 11602 SourceLocation Loc, 11603 bool RefersToEnclosingLocal) { 11604 CXXRecordDecl *Lambda = LSI->Lambda; 11605 11606 // Build the non-static data member. 11607 FieldDecl *Field 11608 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11609 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11610 0, false, ICIS_NoInit); 11611 Field->setImplicit(true); 11612 Field->setAccess(AS_private); 11613 Lambda->addDecl(Field); 11614 11615 // C++11 [expr.prim.lambda]p21: 11616 // When the lambda-expression is evaluated, the entities that 11617 // are captured by copy are used to direct-initialize each 11618 // corresponding non-static data member of the resulting closure 11619 // object. (For array members, the array elements are 11620 // direct-initialized in increasing subscript order.) These 11621 // initializations are performed in the (unspecified) order in 11622 // which the non-static data members are declared. 11623 11624 // Introduce a new evaluation context for the initialization, so 11625 // that temporaries introduced as part of the capture are retained 11626 // to be re-"exported" from the lambda expression itself. 11627 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11628 11629 // C++ [expr.prim.labda]p12: 11630 // An entity captured by a lambda-expression is odr-used (3.2) in 11631 // the scope containing the lambda-expression. 11632 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11633 DeclRefType, VK_LValue, Loc); 11634 Var->setReferenced(true); 11635 Var->markUsed(S.Context); 11636 11637 // When the field has array type, create index variables for each 11638 // dimension of the array. We use these index variables to subscript 11639 // the source array, and other clients (e.g., CodeGen) will perform 11640 // the necessary iteration with these index variables. 11641 SmallVector<VarDecl *, 4> IndexVariables; 11642 QualType BaseType = FieldType; 11643 QualType SizeType = S.Context.getSizeType(); 11644 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11645 while (const ConstantArrayType *Array 11646 = S.Context.getAsConstantArrayType(BaseType)) { 11647 // Create the iteration variable for this array index. 11648 IdentifierInfo *IterationVarName = 0; 11649 { 11650 SmallString<8> Str; 11651 llvm::raw_svector_ostream OS(Str); 11652 OS << "__i" << IndexVariables.size(); 11653 IterationVarName = &S.Context.Idents.get(OS.str()); 11654 } 11655 VarDecl *IterationVar 11656 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11657 IterationVarName, SizeType, 11658 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11659 SC_None); 11660 IndexVariables.push_back(IterationVar); 11661 LSI->ArrayIndexVars.push_back(IterationVar); 11662 11663 // Create a reference to the iteration variable. 11664 ExprResult IterationVarRef 11665 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11666 assert(!IterationVarRef.isInvalid() && 11667 "Reference to invented variable cannot fail!"); 11668 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11669 assert(!IterationVarRef.isInvalid() && 11670 "Conversion of invented variable cannot fail!"); 11671 11672 // Subscript the array with this iteration variable. 11673 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11674 Ref, Loc, IterationVarRef.take(), Loc); 11675 if (Subscript.isInvalid()) { 11676 S.CleanupVarDeclMarking(); 11677 S.DiscardCleanupsInEvaluationContext(); 11678 return ExprError(); 11679 } 11680 11681 Ref = Subscript.take(); 11682 BaseType = Array->getElementType(); 11683 } 11684 11685 // Construct the entity that we will be initializing. For an array, this 11686 // will be first element in the array, which may require several levels 11687 // of array-subscript entities. 11688 SmallVector<InitializedEntity, 4> Entities; 11689 Entities.reserve(1 + IndexVariables.size()); 11690 Entities.push_back( 11691 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11692 Field->getType(), Loc)); 11693 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11694 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11695 0, 11696 Entities.back())); 11697 11698 InitializationKind InitKind 11699 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11700 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11701 ExprResult Result(true); 11702 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11703 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11704 11705 // If this initialization requires any cleanups (e.g., due to a 11706 // default argument to a copy constructor), note that for the 11707 // lambda. 11708 if (S.ExprNeedsCleanups) 11709 LSI->ExprNeedsCleanups = true; 11710 11711 // Exit the expression evaluation context used for the capture. 11712 S.CleanupVarDeclMarking(); 11713 S.DiscardCleanupsInEvaluationContext(); 11714 return Result; 11715} 11716 11717 11718 11719/// \brief Capture the given variable in the lambda. 11720static bool captureInLambda(LambdaScopeInfo *LSI, 11721 VarDecl *Var, 11722 SourceLocation Loc, 11723 const bool BuildAndDiagnose, 11724 QualType &CaptureType, 11725 QualType &DeclRefType, 11726 const bool RefersToEnclosingLocal, 11727 const Sema::TryCaptureKind Kind, 11728 SourceLocation EllipsisLoc, 11729 const bool IsTopScope, 11730 Sema &S) { 11731 11732 // Determine whether we are capturing by reference or by value. 11733 bool ByRef = false; 11734 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11735 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11736 } else { 11737 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11738 } 11739 11740 // Compute the type of the field that will capture this variable. 11741 if (ByRef) { 11742 // C++11 [expr.prim.lambda]p15: 11743 // An entity is captured by reference if it is implicitly or 11744 // explicitly captured but not captured by copy. It is 11745 // unspecified whether additional unnamed non-static data 11746 // members are declared in the closure type for entities 11747 // captured by reference. 11748 // 11749 // FIXME: It is not clear whether we want to build an lvalue reference 11750 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11751 // to do the former, while EDG does the latter. Core issue 1249 will 11752 // clarify, but for now we follow GCC because it's a more permissive and 11753 // easily defensible position. 11754 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11755 } else { 11756 // C++11 [expr.prim.lambda]p14: 11757 // For each entity captured by copy, an unnamed non-static 11758 // data member is declared in the closure type. The 11759 // declaration order of these members is unspecified. The type 11760 // of such a data member is the type of the corresponding 11761 // captured entity if the entity is not a reference to an 11762 // object, or the referenced type otherwise. [Note: If the 11763 // captured entity is a reference to a function, the 11764 // corresponding data member is also a reference to a 11765 // function. - end note ] 11766 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11767 if (!RefType->getPointeeType()->isFunctionType()) 11768 CaptureType = RefType->getPointeeType(); 11769 } 11770 11771 // Forbid the lambda copy-capture of autoreleasing variables. 11772 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11773 if (BuildAndDiagnose) { 11774 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11775 S.Diag(Var->getLocation(), diag::note_previous_decl) 11776 << Var->getDeclName(); 11777 } 11778 return false; 11779 } 11780 11781 if (S.RequireNonAbstractType(Loc, CaptureType, 11782 diag::err_capture_of_abstract_type)) 11783 return false; 11784 } 11785 11786 // Capture this variable in the lambda. 11787 Expr *CopyExpr = 0; 11788 if (BuildAndDiagnose) { 11789 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11790 CaptureType, DeclRefType, Loc, 11791 RefersToEnclosingLocal); 11792 if (!Result.isInvalid()) 11793 CopyExpr = Result.take(); 11794 } 11795 11796 // Compute the type of a reference to this captured variable. 11797 if (ByRef) 11798 DeclRefType = CaptureType.getNonReferenceType(); 11799 else { 11800 // C++ [expr.prim.lambda]p5: 11801 // The closure type for a lambda-expression has a public inline 11802 // function call operator [...]. This function call operator is 11803 // declared const (9.3.1) if and only if the lambda-expression���s 11804 // parameter-declaration-clause is not followed by mutable. 11805 DeclRefType = CaptureType.getNonReferenceType(); 11806 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11807 DeclRefType.addConst(); 11808 } 11809 11810 // Add the capture. 11811 if (BuildAndDiagnose) 11812 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11813 Loc, EllipsisLoc, CaptureType, CopyExpr); 11814 11815 return true; 11816} 11817 11818 11819bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11820 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11821 bool BuildAndDiagnose, 11822 QualType &CaptureType, 11823 QualType &DeclRefType, 11824 const unsigned *const FunctionScopeIndexToStopAt) { 11825 bool Nested = false; 11826 11827 DeclContext *DC = CurContext; 11828 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11829 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 11830 // We need to sync up the Declaration Context with the 11831 // FunctionScopeIndexToStopAt 11832 if (FunctionScopeIndexToStopAt) { 11833 unsigned FSIndex = FunctionScopes.size() - 1; 11834 while (FSIndex != MaxFunctionScopesIndex) { 11835 DC = getLambdaAwareParentOfDeclContext(DC); 11836 --FSIndex; 11837 } 11838 } 11839 11840 11841 // If the variable is declared in the current context (and is not an 11842 // init-capture), there is no need to capture it. 11843 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11844 if (!Var->hasLocalStorage()) return true; 11845 11846 // Walk up the stack to determine whether we can capture the variable, 11847 // performing the "simple" checks that don't depend on type. We stop when 11848 // we've either hit the declared scope of the variable or find an existing 11849 // capture of that variable. We start from the innermost capturing-entity 11850 // (the DC) and ensure that all intervening capturing-entities 11851 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11852 // declcontext can either capture the variable or have already captured 11853 // the variable. 11854 CaptureType = Var->getType(); 11855 DeclRefType = CaptureType.getNonReferenceType(); 11856 bool Explicit = (Kind != TryCapture_Implicit); 11857 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11858 do { 11859 // Only block literals, captured statements, and lambda expressions can 11860 // capture; other scopes don't work. 11861 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11862 ExprLoc, 11863 BuildAndDiagnose, 11864 *this); 11865 if (!ParentDC) return true; 11866 11867 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 11868 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 11869 11870 11871 // Check whether we've already captured it. 11872 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 11873 DeclRefType)) 11874 break; 11875 // If we are instantiating a generic lambda call operator body, 11876 // we do not want to capture new variables. What was captured 11877 // during either a lambdas transformation or initial parsing 11878 // should be used. 11879 if (isGenericLambdaCallOperatorSpecialization(DC)) { 11880 if (BuildAndDiagnose) { 11881 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11882 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 11883 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 11884 Diag(Var->getLocation(), diag::note_previous_decl) 11885 << Var->getDeclName(); 11886 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 11887 } else 11888 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 11889 } 11890 return true; 11891 } 11892 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11893 // certain types of variables (unnamed, variably modified types etc.) 11894 // so check for eligibility. 11895 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 11896 return true; 11897 11898 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11899 // No capture-default, and this is not an explicit capture 11900 // so cannot capture this variable. 11901 if (BuildAndDiagnose) { 11902 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 11903 Diag(Var->getLocation(), diag::note_previous_decl) 11904 << Var->getDeclName(); 11905 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11906 diag::note_lambda_decl); 11907 // FIXME: If we error out because an outer lambda can not implicitly 11908 // capture a variable that an inner lambda explicitly captures, we 11909 // should have the inner lambda do the explicit capture - because 11910 // it makes for cleaner diagnostics later. This would purely be done 11911 // so that the diagnostic does not misleadingly claim that a variable 11912 // can not be captured by a lambda implicitly even though it is captured 11913 // explicitly. Suggestion: 11914 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 11915 // at the function head 11916 // - cache the StartingDeclContext - this must be a lambda 11917 // - captureInLambda in the innermost lambda the variable. 11918 } 11919 return true; 11920 } 11921 11922 FunctionScopesIndex--; 11923 DC = ParentDC; 11924 Explicit = false; 11925 } while (!Var->getDeclContext()->Equals(DC)); 11926 11927 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 11928 // computing the type of the capture at each step, checking type-specific 11929 // requirements, and adding captures if requested. 11930 // If the variable had already been captured previously, we start capturing 11931 // at the lambda nested within that one. 11932 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 11933 ++I) { 11934 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11935 11936 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 11937 if (!captureInBlock(BSI, Var, ExprLoc, 11938 BuildAndDiagnose, CaptureType, 11939 DeclRefType, Nested, *this)) 11940 return true; 11941 Nested = true; 11942 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11943 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 11944 BuildAndDiagnose, CaptureType, 11945 DeclRefType, Nested, *this)) 11946 return true; 11947 Nested = true; 11948 } else { 11949 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11950 if (!captureInLambda(LSI, Var, ExprLoc, 11951 BuildAndDiagnose, CaptureType, 11952 DeclRefType, Nested, Kind, EllipsisLoc, 11953 /*IsTopScope*/I == N - 1, *this)) 11954 return true; 11955 Nested = true; 11956 } 11957 } 11958 return false; 11959} 11960 11961bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11962 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11963 QualType CaptureType; 11964 QualType DeclRefType; 11965 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11966 /*BuildAndDiagnose=*/true, CaptureType, 11967 DeclRefType, 0); 11968} 11969 11970QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11971 QualType CaptureType; 11972 QualType DeclRefType; 11973 11974 // Determine whether we can capture this variable. 11975 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11976 /*BuildAndDiagnose=*/false, CaptureType, 11977 DeclRefType, 0)) 11978 return QualType(); 11979 11980 return DeclRefType; 11981} 11982 11983 11984 11985// If either the type of the variable or the initializer is dependent, 11986// return false. Otherwise, determine whether the variable is a constant 11987// expression. Use this if you need to know if a variable that might or 11988// might not be dependent is truly a constant expression. 11989static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 11990 ASTContext &Context) { 11991 11992 if (Var->getType()->isDependentType()) 11993 return false; 11994 const VarDecl *DefVD = 0; 11995 Var->getAnyInitializer(DefVD); 11996 if (!DefVD) 11997 return false; 11998 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 11999 Expr *Init = cast<Expr>(Eval->Value); 12000 if (Init->isValueDependent()) 12001 return false; 12002 return IsVariableAConstantExpression(Var, Context); 12003} 12004 12005 12006void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12007 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12008 // an object that satisfies the requirements for appearing in a 12009 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12010 // is immediately applied." This function handles the lvalue-to-rvalue 12011 // conversion part. 12012 MaybeODRUseExprs.erase(E->IgnoreParens()); 12013 12014 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12015 // to a variable that is a constant expression, and if so, identify it as 12016 // a reference to a variable that does not involve an odr-use of that 12017 // variable. 12018 if (LambdaScopeInfo *LSI = getCurLambda()) { 12019 Expr *SansParensExpr = E->IgnoreParens(); 12020 VarDecl *Var = 0; 12021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12022 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12023 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12024 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12025 12026 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12027 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12028 } 12029} 12030 12031ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12032 if (!Res.isUsable()) 12033 return Res; 12034 12035 // If a constant-expression is a reference to a variable where we delay 12036 // deciding whether it is an odr-use, just assume we will apply the 12037 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12038 // (a non-type template argument), we have special handling anyway. 12039 UpdateMarkingForLValueToRValue(Res.get()); 12040 return Res; 12041} 12042 12043void Sema::CleanupVarDeclMarking() { 12044 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12045 e = MaybeODRUseExprs.end(); 12046 i != e; ++i) { 12047 VarDecl *Var; 12048 SourceLocation Loc; 12049 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12050 Var = cast<VarDecl>(DRE->getDecl()); 12051 Loc = DRE->getLocation(); 12052 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12053 Var = cast<VarDecl>(ME->getMemberDecl()); 12054 Loc = ME->getMemberLoc(); 12055 } else { 12056 llvm_unreachable("Unexpcted expression"); 12057 } 12058 12059 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0); 12060 } 12061 12062 MaybeODRUseExprs.clear(); 12063} 12064 12065 12066static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12067 VarDecl *Var, Expr *E) { 12068 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12069 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12070 Var->setReferenced(); 12071 12072 // If the context is not PotentiallyEvaluated and not Unevaluated 12073 // (i.e PotentiallyEvaluatedIfUsed) do not bother to consider variables 12074 // in this context for odr-use unless we are within a lambda. 12075 // If we don't know whether the context is potentially evaluated or not 12076 // (for e.g., if we're in a generic lambda), we want to add a potential 12077 // capture and eventually analyze for odr-use. 12078 // We should also be able to analyze certain constructs in a non-generic 12079 // lambda setting for potential odr-use and capture violation: 12080 // template<class T> void foo(T t) { 12081 // auto L = [](int i) { return t; }; 12082 // } 12083 // 12084 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12085 12086 if (SemaRef.isUnevaluatedContext()) return; 12087 12088 const bool refersToEnclosingScope = 12089 (SemaRef.CurContext != Var->getDeclContext() && 12090 Var->getDeclContext()->isFunctionOrMethod()); 12091 if (!refersToEnclosingScope) return; 12092 12093 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12094 // If a variable could potentially be odr-used, defer marking it so 12095 // until we finish analyzing the full expression for any lvalue-to-rvalue 12096 // or discarded value conversions that would obviate odr-use. 12097 // Add it to the list of potential captures that will be analyzed 12098 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12099 // unless the variable is a reference that was initialized by a constant 12100 // expression (this will never need to be captured or odr-used). 12101 const bool IsConstantExpr = IsVariableNonDependentAndAConstantExpression( 12102 Var, SemaRef.Context); 12103 assert(E && "Capture variable should be used in an expression."); 12104 if (!IsConstantExpr || !Var->getType()->isReferenceType()) 12105 LSI->addPotentialCapture(E->IgnoreParens()); 12106 } 12107 return; 12108 } 12109 12110 VarTemplateSpecializationDecl *VarSpec = 12111 dyn_cast<VarTemplateSpecializationDecl>(Var); 12112 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12113 "Can't instantiate a partial template specialization."); 12114 12115 // Implicit instantiation of static data members, static data member 12116 // templates of class templates, and variable template specializations. 12117 // Delay instantiations of variable templates, except for those 12118 // that could be used in a constant expression. 12119 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12120 if (isTemplateInstantiation(TSK)) { 12121 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12122 12123 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12124 if (Var->getPointOfInstantiation().isInvalid()) { 12125 // This is a modification of an existing AST node. Notify listeners. 12126 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12127 L->StaticDataMemberInstantiated(Var); 12128 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12129 // Don't bother trying to instantiate it again, unless we might need 12130 // its initializer before we get to the end of the TU. 12131 TryInstantiating = false; 12132 } 12133 12134 if (Var->getPointOfInstantiation().isInvalid()) 12135 Var->setTemplateSpecializationKind(TSK, Loc); 12136 12137 if (TryInstantiating) { 12138 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12139 bool InstantiationDependent = false; 12140 bool IsNonDependent = 12141 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12142 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12143 : true; 12144 12145 // Do not instantiate specializations that are still type-dependent. 12146 if (IsNonDependent) { 12147 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12148 // Do not defer instantiations of variables which could be used in a 12149 // constant expression. 12150 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12151 } else { 12152 SemaRef.PendingInstantiations 12153 .push_back(std::make_pair(Var, PointOfInstantiation)); 12154 } 12155 } 12156 } 12157 } 12158 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12159 // the requirements for appearing in a constant expression (5.19) and, if 12160 // it is an object, the lvalue-to-rvalue conversion (4.1) 12161 // is immediately applied." We check the first part here, and 12162 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12163 // Note that we use the C++11 definition everywhere because nothing in 12164 // C++03 depends on whether we get the C++03 version correct. The second 12165 // part does not apply to references, since they are not objects. 12166 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12167 // A reference initialized by a constant expression can never be 12168 // odr-used, so simply ignore it. 12169 // But a non-reference might get odr-used if it doesn't undergo 12170 // an lvalue-to-rvalue or is discarded, so track it. 12171 if (!Var->getType()->isReferenceType()) 12172 SemaRef.MaybeODRUseExprs.insert(E); 12173 } 12174 else 12175 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0); 12176} 12177 12178/// \brief Mark a variable referenced, and check whether it is odr-used 12179/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12180/// used directly for normal expressions referring to VarDecl. 12181void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12182 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12183} 12184 12185static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12186 Decl *D, Expr *E, bool OdrUse) { 12187 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12188 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12189 return; 12190 } 12191 12192 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12193 12194 // If this is a call to a method via a cast, also mark the method in the 12195 // derived class used in case codegen can devirtualize the call. 12196 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12197 if (!ME) 12198 return; 12199 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12200 if (!MD) 12201 return; 12202 const Expr *Base = ME->getBase(); 12203 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12204 if (!MostDerivedClassDecl) 12205 return; 12206 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12207 if (!DM || DM->isPure()) 12208 return; 12209 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12210} 12211 12212/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12213void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12214 // TODO: update this with DR# once a defect report is filed. 12215 // C++11 defect. The address of a pure member should not be an ODR use, even 12216 // if it's a qualified reference. 12217 bool OdrUse = true; 12218 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12219 if (Method->isVirtual()) 12220 OdrUse = false; 12221 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12222} 12223 12224/// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12225void Sema::MarkMemberReferenced(MemberExpr *E) { 12226 // C++11 [basic.def.odr]p2: 12227 // A non-overloaded function whose name appears as a potentially-evaluated 12228 // expression or a member of a set of candidate functions, if selected by 12229 // overload resolution when referred to from a potentially-evaluated 12230 // expression, is odr-used, unless it is a pure virtual function and its 12231 // name is not explicitly qualified. 12232 bool OdrUse = true; 12233 if (!E->hasQualifier()) { 12234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12235 if (Method->isPure()) 12236 OdrUse = false; 12237 } 12238 SourceLocation Loc = E->getMemberLoc().isValid() ? 12239 E->getMemberLoc() : E->getLocStart(); 12240 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12241} 12242 12243/// \brief Perform marking for a reference to an arbitrary declaration. It 12244/// marks the declaration referenced, and performs odr-use checking for functions 12245/// and variables. This method should not be used when building an normal 12246/// expression which refers to a variable. 12247void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12248 if (OdrUse) { 12249 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12250 MarkVariableReferenced(Loc, VD); 12251 return; 12252 } 12253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12254 MarkFunctionReferenced(Loc, FD); 12255 return; 12256 } 12257 } 12258 D->setReferenced(); 12259} 12260 12261namespace { 12262 // Mark all of the declarations referenced 12263 // FIXME: Not fully implemented yet! We need to have a better understanding 12264 // of when we're entering 12265 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12266 Sema &S; 12267 SourceLocation Loc; 12268 12269 public: 12270 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12271 12272 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12273 12274 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12275 bool TraverseRecordType(RecordType *T); 12276 }; 12277} 12278 12279bool MarkReferencedDecls::TraverseTemplateArgument( 12280 const TemplateArgument &Arg) { 12281 if (Arg.getKind() == TemplateArgument::Declaration) { 12282 if (Decl *D = Arg.getAsDecl()) 12283 S.MarkAnyDeclReferenced(Loc, D, true); 12284 } 12285 12286 return Inherited::TraverseTemplateArgument(Arg); 12287} 12288 12289bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12290 if (ClassTemplateSpecializationDecl *Spec 12291 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12292 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12293 return TraverseTemplateArguments(Args.data(), Args.size()); 12294 } 12295 12296 return true; 12297} 12298 12299void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12300 MarkReferencedDecls Marker(*this, Loc); 12301 Marker.TraverseType(Context.getCanonicalType(T)); 12302} 12303 12304namespace { 12305 /// \brief Helper class that marks all of the declarations referenced by 12306 /// potentially-evaluated subexpressions as "referenced". 12307 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12308 Sema &S; 12309 bool SkipLocalVariables; 12310 12311 public: 12312 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12313 12314 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12315 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12316 12317 void VisitDeclRefExpr(DeclRefExpr *E) { 12318 // If we were asked not to visit local variables, don't. 12319 if (SkipLocalVariables) { 12320 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12321 if (VD->hasLocalStorage()) 12322 return; 12323 } 12324 12325 S.MarkDeclRefReferenced(E); 12326 } 12327 12328 void VisitMemberExpr(MemberExpr *E) { 12329 S.MarkMemberReferenced(E); 12330 Inherited::VisitMemberExpr(E); 12331 } 12332 12333 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12334 S.MarkFunctionReferenced(E->getLocStart(), 12335 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12336 Visit(E->getSubExpr()); 12337 } 12338 12339 void VisitCXXNewExpr(CXXNewExpr *E) { 12340 if (E->getOperatorNew()) 12341 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12342 if (E->getOperatorDelete()) 12343 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12344 Inherited::VisitCXXNewExpr(E); 12345 } 12346 12347 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12348 if (E->getOperatorDelete()) 12349 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12350 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12351 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12352 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12353 S.MarkFunctionReferenced(E->getLocStart(), 12354 S.LookupDestructor(Record)); 12355 } 12356 12357 Inherited::VisitCXXDeleteExpr(E); 12358 } 12359 12360 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12361 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12362 Inherited::VisitCXXConstructExpr(E); 12363 } 12364 12365 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12366 Visit(E->getExpr()); 12367 } 12368 12369 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12370 Inherited::VisitImplicitCastExpr(E); 12371 12372 if (E->getCastKind() == CK_LValueToRValue) 12373 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12374 } 12375 }; 12376} 12377 12378/// \brief Mark any declarations that appear within this expression or any 12379/// potentially-evaluated subexpressions as "referenced". 12380/// 12381/// \param SkipLocalVariables If true, don't mark local variables as 12382/// 'referenced'. 12383void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12384 bool SkipLocalVariables) { 12385 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12386} 12387 12388/// \brief Emit a diagnostic that describes an effect on the run-time behavior 12389/// of the program being compiled. 12390/// 12391/// This routine emits the given diagnostic when the code currently being 12392/// type-checked is "potentially evaluated", meaning that there is a 12393/// possibility that the code will actually be executable. Code in sizeof() 12394/// expressions, code used only during overload resolution, etc., are not 12395/// potentially evaluated. This routine will suppress such diagnostics or, 12396/// in the absolutely nutty case of potentially potentially evaluated 12397/// expressions (C++ typeid), queue the diagnostic to potentially emit it 12398/// later. 12399/// 12400/// This routine should be used for all diagnostics that describe the run-time 12401/// behavior of a program, such as passing a non-POD value through an ellipsis. 12402/// Failure to do so will likely result in spurious diagnostics or failures 12403/// during overload resolution or within sizeof/alignof/typeof/typeid. 12404bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12405 const PartialDiagnostic &PD) { 12406 switch (ExprEvalContexts.back().Context) { 12407 case Unevaluated: 12408 case UnevaluatedAbstract: 12409 // The argument will never be evaluated, so don't complain. 12410 break; 12411 12412 case ConstantEvaluated: 12413 // Relevant diagnostics should be produced by constant evaluation. 12414 break; 12415 12416 case PotentiallyEvaluated: 12417 case PotentiallyEvaluatedIfUsed: 12418 if (Statement && getCurFunctionOrMethodDecl()) { 12419 FunctionScopes.back()->PossiblyUnreachableDiags. 12420 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12421 } 12422 else 12423 Diag(Loc, PD); 12424 12425 return true; 12426 } 12427 12428 return false; 12429} 12430 12431bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12432 CallExpr *CE, FunctionDecl *FD) { 12433 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12434 return false; 12435 12436 // If we're inside a decltype's expression, don't check for a valid return 12437 // type or construct temporaries until we know whether this is the last call. 12438 if (ExprEvalContexts.back().IsDecltype) { 12439 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12440 return false; 12441 } 12442 12443 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12444 FunctionDecl *FD; 12445 CallExpr *CE; 12446 12447 public: 12448 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12449 : FD(FD), CE(CE) { } 12450 12451 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12452 if (!FD) { 12453 S.Diag(Loc, diag::err_call_incomplete_return) 12454 << T << CE->getSourceRange(); 12455 return; 12456 } 12457 12458 S.Diag(Loc, diag::err_call_function_incomplete_return) 12459 << CE->getSourceRange() << FD->getDeclName() << T; 12460 S.Diag(FD->getLocation(), 12461 diag::note_function_with_incomplete_return_type_declared_here) 12462 << FD->getDeclName(); 12463 } 12464 } Diagnoser(FD, CE); 12465 12466 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12467 return true; 12468 12469 return false; 12470} 12471 12472// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12473// will prevent this condition from triggering, which is what we want. 12474void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12475 SourceLocation Loc; 12476 12477 unsigned diagnostic = diag::warn_condition_is_assignment; 12478 bool IsOrAssign = false; 12479 12480 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12481 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12482 return; 12483 12484 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12485 12486 // Greylist some idioms by putting them into a warning subcategory. 12487 if (ObjCMessageExpr *ME 12488 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12489 Selector Sel = ME->getSelector(); 12490 12491 // self = [<foo> init...] 12492 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12493 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12494 12495 // <foo> = [<bar> nextObject] 12496 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12497 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12498 } 12499 12500 Loc = Op->getOperatorLoc(); 12501 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12502 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12503 return; 12504 12505 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12506 Loc = Op->getOperatorLoc(); 12507 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12508 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12509 else { 12510 // Not an assignment. 12511 return; 12512 } 12513 12514 Diag(Loc, diagnostic) << E->getSourceRange(); 12515 12516 SourceLocation Open = E->getLocStart(); 12517 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12518 Diag(Loc, diag::note_condition_assign_silence) 12519 << FixItHint::CreateInsertion(Open, "(") 12520 << FixItHint::CreateInsertion(Close, ")"); 12521 12522 if (IsOrAssign) 12523 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12524 << FixItHint::CreateReplacement(Loc, "!="); 12525 else 12526 Diag(Loc, diag::note_condition_assign_to_comparison) 12527 << FixItHint::CreateReplacement(Loc, "=="); 12528} 12529 12530/// \brief Redundant parentheses over an equality comparison can indicate 12531/// that the user intended an assignment used as condition. 12532void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12533 // Don't warn if the parens came from a macro. 12534 SourceLocation parenLoc = ParenE->getLocStart(); 12535 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12536 return; 12537 // Don't warn for dependent expressions. 12538 if (ParenE->isTypeDependent()) 12539 return; 12540 12541 Expr *E = ParenE->IgnoreParens(); 12542 12543 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12544 if (opE->getOpcode() == BO_EQ && 12545 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12546 == Expr::MLV_Valid) { 12547 SourceLocation Loc = opE->getOperatorLoc(); 12548 12549 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12550 SourceRange ParenERange = ParenE->getSourceRange(); 12551 Diag(Loc, diag::note_equality_comparison_silence) 12552 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12553 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12554 Diag(Loc, diag::note_equality_comparison_to_assign) 12555 << FixItHint::CreateReplacement(Loc, "="); 12556 } 12557} 12558 12559ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12560 DiagnoseAssignmentAsCondition(E); 12561 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12562 DiagnoseEqualityWithExtraParens(parenE); 12563 12564 ExprResult result = CheckPlaceholderExpr(E); 12565 if (result.isInvalid()) return ExprError(); 12566 E = result.take(); 12567 12568 if (!E->isTypeDependent()) { 12569 if (getLangOpts().CPlusPlus) 12570 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12571 12572 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12573 if (ERes.isInvalid()) 12574 return ExprError(); 12575 E = ERes.take(); 12576 12577 QualType T = E->getType(); 12578 if (!T->isScalarType()) { // C99 6.8.4.1p1 12579 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12580 << T << E->getSourceRange(); 12581 return ExprError(); 12582 } 12583 } 12584 12585 return Owned(E); 12586} 12587 12588ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12589 Expr *SubExpr) { 12590 if (!SubExpr) 12591 return ExprError(); 12592 12593 return CheckBooleanCondition(SubExpr, Loc); 12594} 12595 12596namespace { 12597 /// A visitor for rebuilding a call to an __unknown_any expression 12598 /// to have an appropriate type. 12599 struct RebuildUnknownAnyFunction 12600 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12601 12602 Sema &S; 12603 12604 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12605 12606 ExprResult VisitStmt(Stmt *S) { 12607 llvm_unreachable("unexpected statement!"); 12608 } 12609 12610 ExprResult VisitExpr(Expr *E) { 12611 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12612 << E->getSourceRange(); 12613 return ExprError(); 12614 } 12615 12616 /// Rebuild an expression which simply semantically wraps another 12617 /// expression which it shares the type and value kind of. 12618 template <class T> ExprResult rebuildSugarExpr(T *E) { 12619 ExprResult SubResult = Visit(E->getSubExpr()); 12620 if (SubResult.isInvalid()) return ExprError(); 12621 12622 Expr *SubExpr = SubResult.take(); 12623 E->setSubExpr(SubExpr); 12624 E->setType(SubExpr->getType()); 12625 E->setValueKind(SubExpr->getValueKind()); 12626 assert(E->getObjectKind() == OK_Ordinary); 12627 return E; 12628 } 12629 12630 ExprResult VisitParenExpr(ParenExpr *E) { 12631 return rebuildSugarExpr(E); 12632 } 12633 12634 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12635 return rebuildSugarExpr(E); 12636 } 12637 12638 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12639 ExprResult SubResult = Visit(E->getSubExpr()); 12640 if (SubResult.isInvalid()) return ExprError(); 12641 12642 Expr *SubExpr = SubResult.take(); 12643 E->setSubExpr(SubExpr); 12644 E->setType(S.Context.getPointerType(SubExpr->getType())); 12645 assert(E->getValueKind() == VK_RValue); 12646 assert(E->getObjectKind() == OK_Ordinary); 12647 return E; 12648 } 12649 12650 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12651 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12652 12653 E->setType(VD->getType()); 12654 12655 assert(E->getValueKind() == VK_RValue); 12656 if (S.getLangOpts().CPlusPlus && 12657 !(isa<CXXMethodDecl>(VD) && 12658 cast<CXXMethodDecl>(VD)->isInstance())) 12659 E->setValueKind(VK_LValue); 12660 12661 return E; 12662 } 12663 12664 ExprResult VisitMemberExpr(MemberExpr *E) { 12665 return resolveDecl(E, E->getMemberDecl()); 12666 } 12667 12668 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12669 return resolveDecl(E, E->getDecl()); 12670 } 12671 }; 12672} 12673 12674/// Given a function expression of unknown-any type, try to rebuild it 12675/// to have a function type. 12676static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12677 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12678 if (Result.isInvalid()) return ExprError(); 12679 return S.DefaultFunctionArrayConversion(Result.take()); 12680} 12681 12682namespace { 12683 /// A visitor for rebuilding an expression of type __unknown_anytype 12684 /// into one which resolves the type directly on the referring 12685 /// expression. Strict preservation of the original source 12686 /// structure is not a goal. 12687 struct RebuildUnknownAnyExpr 12688 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12689 12690 Sema &S; 12691 12692 /// The current destination type. 12693 QualType DestType; 12694 12695 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12696 : S(S), DestType(CastType) {} 12697 12698 ExprResult VisitStmt(Stmt *S) { 12699 llvm_unreachable("unexpected statement!"); 12700 } 12701 12702 ExprResult VisitExpr(Expr *E) { 12703 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12704 << E->getSourceRange(); 12705 return ExprError(); 12706 } 12707 12708 ExprResult VisitCallExpr(CallExpr *E); 12709 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12710 12711 /// Rebuild an expression which simply semantically wraps another 12712 /// expression which it shares the type and value kind of. 12713 template <class T> ExprResult rebuildSugarExpr(T *E) { 12714 ExprResult SubResult = Visit(E->getSubExpr()); 12715 if (SubResult.isInvalid()) return ExprError(); 12716 Expr *SubExpr = SubResult.take(); 12717 E->setSubExpr(SubExpr); 12718 E->setType(SubExpr->getType()); 12719 E->setValueKind(SubExpr->getValueKind()); 12720 assert(E->getObjectKind() == OK_Ordinary); 12721 return E; 12722 } 12723 12724 ExprResult VisitParenExpr(ParenExpr *E) { 12725 return rebuildSugarExpr(E); 12726 } 12727 12728 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12729 return rebuildSugarExpr(E); 12730 } 12731 12732 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12733 const PointerType *Ptr = DestType->getAs<PointerType>(); 12734 if (!Ptr) { 12735 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12736 << E->getSourceRange(); 12737 return ExprError(); 12738 } 12739 assert(E->getValueKind() == VK_RValue); 12740 assert(E->getObjectKind() == OK_Ordinary); 12741 E->setType(DestType); 12742 12743 // Build the sub-expression as if it were an object of the pointee type. 12744 DestType = Ptr->getPointeeType(); 12745 ExprResult SubResult = Visit(E->getSubExpr()); 12746 if (SubResult.isInvalid()) return ExprError(); 12747 E->setSubExpr(SubResult.take()); 12748 return E; 12749 } 12750 12751 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12752 12753 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12754 12755 ExprResult VisitMemberExpr(MemberExpr *E) { 12756 return resolveDecl(E, E->getMemberDecl()); 12757 } 12758 12759 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12760 return resolveDecl(E, E->getDecl()); 12761 } 12762 }; 12763} 12764 12765/// Rebuilds a call expression which yielded __unknown_anytype. 12766ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12767 Expr *CalleeExpr = E->getCallee(); 12768 12769 enum FnKind { 12770 FK_MemberFunction, 12771 FK_FunctionPointer, 12772 FK_BlockPointer 12773 }; 12774 12775 FnKind Kind; 12776 QualType CalleeType = CalleeExpr->getType(); 12777 if (CalleeType == S.Context.BoundMemberTy) { 12778 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12779 Kind = FK_MemberFunction; 12780 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12781 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12782 CalleeType = Ptr->getPointeeType(); 12783 Kind = FK_FunctionPointer; 12784 } else { 12785 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12786 Kind = FK_BlockPointer; 12787 } 12788 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12789 12790 // Verify that this is a legal result type of a function. 12791 if (DestType->isArrayType() || DestType->isFunctionType()) { 12792 unsigned diagID = diag::err_func_returning_array_function; 12793 if (Kind == FK_BlockPointer) 12794 diagID = diag::err_block_returning_array_function; 12795 12796 S.Diag(E->getExprLoc(), diagID) 12797 << DestType->isFunctionType() << DestType; 12798 return ExprError(); 12799 } 12800 12801 // Otherwise, go ahead and set DestType as the call's result. 12802 E->setType(DestType.getNonLValueExprType(S.Context)); 12803 E->setValueKind(Expr::getValueKindForType(DestType)); 12804 assert(E->getObjectKind() == OK_Ordinary); 12805 12806 // Rebuild the function type, replacing the result type with DestType. 12807 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12808 if (Proto) { 12809 // __unknown_anytype(...) is a special case used by the debugger when 12810 // it has no idea what a function's signature is. 12811 // 12812 // We want to build this call essentially under the K&R 12813 // unprototyped rules, but making a FunctionNoProtoType in C++ 12814 // would foul up all sorts of assumptions. However, we cannot 12815 // simply pass all arguments as variadic arguments, nor can we 12816 // portably just call the function under a non-variadic type; see 12817 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12818 // However, it turns out that in practice it is generally safe to 12819 // call a function declared as "A foo(B,C,D);" under the prototype 12820 // "A foo(B,C,D,...);". The only known exception is with the 12821 // Windows ABI, where any variadic function is implicitly cdecl 12822 // regardless of its normal CC. Therefore we change the parameter 12823 // types to match the types of the arguments. 12824 // 12825 // This is a hack, but it is far superior to moving the 12826 // corresponding target-specific code from IR-gen to Sema/AST. 12827 12828 ArrayRef<QualType> ParamTypes = Proto->getArgTypes(); 12829 SmallVector<QualType, 8> ArgTypes; 12830 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12831 ArgTypes.reserve(E->getNumArgs()); 12832 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12833 Expr *Arg = E->getArg(i); 12834 QualType ArgType = Arg->getType(); 12835 if (E->isLValue()) { 12836 ArgType = S.Context.getLValueReferenceType(ArgType); 12837 } else if (E->isXValue()) { 12838 ArgType = S.Context.getRValueReferenceType(ArgType); 12839 } 12840 ArgTypes.push_back(ArgType); 12841 } 12842 ParamTypes = ArgTypes; 12843 } 12844 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12845 Proto->getExtProtoInfo()); 12846 } else { 12847 DestType = S.Context.getFunctionNoProtoType(DestType, 12848 FnType->getExtInfo()); 12849 } 12850 12851 // Rebuild the appropriate pointer-to-function type. 12852 switch (Kind) { 12853 case FK_MemberFunction: 12854 // Nothing to do. 12855 break; 12856 12857 case FK_FunctionPointer: 12858 DestType = S.Context.getPointerType(DestType); 12859 break; 12860 12861 case FK_BlockPointer: 12862 DestType = S.Context.getBlockPointerType(DestType); 12863 break; 12864 } 12865 12866 // Finally, we can recurse. 12867 ExprResult CalleeResult = Visit(CalleeExpr); 12868 if (!CalleeResult.isUsable()) return ExprError(); 12869 E->setCallee(CalleeResult.take()); 12870 12871 // Bind a temporary if necessary. 12872 return S.MaybeBindToTemporary(E); 12873} 12874 12875ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12876 // Verify that this is a legal result type of a call. 12877 if (DestType->isArrayType() || DestType->isFunctionType()) { 12878 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12879 << DestType->isFunctionType() << DestType; 12880 return ExprError(); 12881 } 12882 12883 // Rewrite the method result type if available. 12884 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12885 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12886 Method->setResultType(DestType); 12887 } 12888 12889 // Change the type of the message. 12890 E->setType(DestType.getNonReferenceType()); 12891 E->setValueKind(Expr::getValueKindForType(DestType)); 12892 12893 return S.MaybeBindToTemporary(E); 12894} 12895 12896ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12897 // The only case we should ever see here is a function-to-pointer decay. 12898 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12899 assert(E->getValueKind() == VK_RValue); 12900 assert(E->getObjectKind() == OK_Ordinary); 12901 12902 E->setType(DestType); 12903 12904 // Rebuild the sub-expression as the pointee (function) type. 12905 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12906 12907 ExprResult Result = Visit(E->getSubExpr()); 12908 if (!Result.isUsable()) return ExprError(); 12909 12910 E->setSubExpr(Result.take()); 12911 return S.Owned(E); 12912 } else if (E->getCastKind() == CK_LValueToRValue) { 12913 assert(E->getValueKind() == VK_RValue); 12914 assert(E->getObjectKind() == OK_Ordinary); 12915 12916 assert(isa<BlockPointerType>(E->getType())); 12917 12918 E->setType(DestType); 12919 12920 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12921 DestType = S.Context.getLValueReferenceType(DestType); 12922 12923 ExprResult Result = Visit(E->getSubExpr()); 12924 if (!Result.isUsable()) return ExprError(); 12925 12926 E->setSubExpr(Result.take()); 12927 return S.Owned(E); 12928 } else { 12929 llvm_unreachable("Unhandled cast type!"); 12930 } 12931} 12932 12933ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12934 ExprValueKind ValueKind = VK_LValue; 12935 QualType Type = DestType; 12936 12937 // We know how to make this work for certain kinds of decls: 12938 12939 // - functions 12940 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12941 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12942 DestType = Ptr->getPointeeType(); 12943 ExprResult Result = resolveDecl(E, VD); 12944 if (Result.isInvalid()) return ExprError(); 12945 return S.ImpCastExprToType(Result.take(), Type, 12946 CK_FunctionToPointerDecay, VK_RValue); 12947 } 12948 12949 if (!Type->isFunctionType()) { 12950 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12951 << VD << E->getSourceRange(); 12952 return ExprError(); 12953 } 12954 12955 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12956 if (MD->isInstance()) { 12957 ValueKind = VK_RValue; 12958 Type = S.Context.BoundMemberTy; 12959 } 12960 12961 // Function references aren't l-values in C. 12962 if (!S.getLangOpts().CPlusPlus) 12963 ValueKind = VK_RValue; 12964 12965 // - variables 12966 } else if (isa<VarDecl>(VD)) { 12967 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12968 Type = RefTy->getPointeeType(); 12969 } else if (Type->isFunctionType()) { 12970 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12971 << VD << E->getSourceRange(); 12972 return ExprError(); 12973 } 12974 12975 // - nothing else 12976 } else { 12977 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12978 << VD << E->getSourceRange(); 12979 return ExprError(); 12980 } 12981 12982 // Modifying the declaration like this is friendly to IR-gen but 12983 // also really dangerous. 12984 VD->setType(DestType); 12985 E->setType(Type); 12986 E->setValueKind(ValueKind); 12987 return S.Owned(E); 12988} 12989 12990/// Check a cast of an unknown-any type. We intentionally only 12991/// trigger this for C-style casts. 12992ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12993 Expr *CastExpr, CastKind &CastKind, 12994 ExprValueKind &VK, CXXCastPath &Path) { 12995 // Rewrite the casted expression from scratch. 12996 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12997 if (!result.isUsable()) return ExprError(); 12998 12999 CastExpr = result.take(); 13000 VK = CastExpr->getValueKind(); 13001 CastKind = CK_NoOp; 13002 13003 return CastExpr; 13004} 13005 13006ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13007 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13008} 13009 13010ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13011 Expr *arg, QualType ¶mType) { 13012 // If the syntactic form of the argument is not an explicit cast of 13013 // any sort, just do default argument promotion. 13014 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13015 if (!castArg) { 13016 ExprResult result = DefaultArgumentPromotion(arg); 13017 if (result.isInvalid()) return ExprError(); 13018 paramType = result.get()->getType(); 13019 return result; 13020 } 13021 13022 // Otherwise, use the type that was written in the explicit cast. 13023 assert(!arg->hasPlaceholderType()); 13024 paramType = castArg->getTypeAsWritten(); 13025 13026 // Copy-initialize a parameter of that type. 13027 InitializedEntity entity = 13028 InitializedEntity::InitializeParameter(Context, paramType, 13029 /*consumed*/ false); 13030 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 13031} 13032 13033static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13034 Expr *orig = E; 13035 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13036 while (true) { 13037 E = E->IgnoreParenImpCasts(); 13038 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13039 E = call->getCallee(); 13040 diagID = diag::err_uncasted_call_of_unknown_any; 13041 } else { 13042 break; 13043 } 13044 } 13045 13046 SourceLocation loc; 13047 NamedDecl *d; 13048 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13049 loc = ref->getLocation(); 13050 d = ref->getDecl(); 13051 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13052 loc = mem->getMemberLoc(); 13053 d = mem->getMemberDecl(); 13054 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13055 diagID = diag::err_uncasted_call_of_unknown_any; 13056 loc = msg->getSelectorStartLoc(); 13057 d = msg->getMethodDecl(); 13058 if (!d) { 13059 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13060 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13061 << orig->getSourceRange(); 13062 return ExprError(); 13063 } 13064 } else { 13065 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13066 << E->getSourceRange(); 13067 return ExprError(); 13068 } 13069 13070 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13071 13072 // Never recoverable. 13073 return ExprError(); 13074} 13075 13076/// Check for operands with placeholder types and complain if found. 13077/// Returns true if there was an error and no recovery was possible. 13078ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13079 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13080 if (!placeholderType) return Owned(E); 13081 13082 switch (placeholderType->getKind()) { 13083 13084 // Overloaded expressions. 13085 case BuiltinType::Overload: { 13086 // Try to resolve a single function template specialization. 13087 // This is obligatory. 13088 ExprResult result = Owned(E); 13089 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13090 return result; 13091 13092 // If that failed, try to recover with a call. 13093 } else { 13094 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13095 /*complain*/ true); 13096 return result; 13097 } 13098 } 13099 13100 // Bound member functions. 13101 case BuiltinType::BoundMember: { 13102 ExprResult result = Owned(E); 13103 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13104 /*complain*/ true); 13105 return result; 13106 } 13107 13108 // ARC unbridged casts. 13109 case BuiltinType::ARCUnbridgedCast: { 13110 Expr *realCast = stripARCUnbridgedCast(E); 13111 diagnoseARCUnbridgedCast(realCast); 13112 return Owned(realCast); 13113 } 13114 13115 // Expressions of unknown type. 13116 case BuiltinType::UnknownAny: 13117 return diagnoseUnknownAnyExpr(*this, E); 13118 13119 // Pseudo-objects. 13120 case BuiltinType::PseudoObject: 13121 return checkPseudoObjectRValue(E); 13122 13123 case BuiltinType::BuiltinFn: 13124 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13125 return ExprError(); 13126 13127 // Everything else should be impossible. 13128#define BUILTIN_TYPE(Id, SingletonId) \ 13129 case BuiltinType::Id: 13130#define PLACEHOLDER_TYPE(Id, SingletonId) 13131#include "clang/AST/BuiltinTypes.def" 13132 break; 13133 } 13134 13135 llvm_unreachable("invalid placeholder type!"); 13136} 13137 13138bool Sema::CheckCaseExpression(Expr *E) { 13139 if (E->isTypeDependent()) 13140 return true; 13141 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13142 return E->getType()->isIntegralOrEnumerationType(); 13143 return false; 13144} 13145 13146/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13147ExprResult 13148Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13149 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13150 "Unknown Objective-C Boolean value!"); 13151 QualType BoolT = Context.ObjCBuiltinBoolTy; 13152 if (!Context.getBOOLDecl()) { 13153 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13154 Sema::LookupOrdinaryName); 13155 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13156 NamedDecl *ND = Result.getFoundDecl(); 13157 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13158 Context.setBOOLDecl(TD); 13159 } 13160 } 13161 if (Context.getBOOLDecl()) 13162 BoolT = Context.getBOOLType(); 13163 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13164 BoolT, OpLoc)); 13165} 13166